Remove first or last part of a string in bash

You can use the following option:

${var:start:nr_of_characters}

Combined with ${#var} (the length of the string) can become a powerful command.

Here are some examples where var=abcdefghij

To remove the first 3 characters of $var:

echo ${var:3: ${#var}-3}
defghij

To keep the first 3 characters of $var:

echo ${var:0:3}
abc

To remove last 5 characters of $var:

echo ${var:0:${#var}-5}
abcde

To keep last 4 characters of $var:

echo ${var:${#var}-4:4}
ghij

To keep from the 3rd character to the 7th of

echo ${var:2:5}
cdefg

Happy scripting!

Leave a Reply

Your email address will not be published. Required fields are marked *