Bash replace prefix with spaces

200 views Asked by At

How to remove prefix from string in Bash?

For example:

STRING1="My name is James"
echo "${STRING1}" 
# My name is James

NAME="${STRING1#???}"
echo "${NAME}" 
# James
2

There are 2 answers

1
Ronak Patel On BEST ANSWER

Alternative: FOO=${FOO//$WORDTOREMOVE/}

$ STRING1="My name is James"
$ NAME="${STRING1//My name is /}"
$ echo "${NAME}"
James

Update as per @gniourf_gniourf's suggestion : FOO=${FOO/#$WORDTOREMOVE/}

$ NAME="${STRING1/#My name is /}"
$ echo "${NAME}"
James
3
Andrii Abramov On

To do so, you have to escape special symbols in the prefix string.

NAME="${STRING1#My\ name\ is\ }"
echo "${NAME}"
# James

The same thing with suffices.