21/09/2019

[bash] Substring with parameter expansion

In bash it is possible to use parameter expansion with syntax ${expression}to perform a substring operation. Here are some examples, the first value MUST be a variable.

To cut out some text from the BEGINNING of the string:

result=${string#string_to_cut}

For example

string=groglogs
result=${string#grog}

will return logs

To cut out some text BEFORE the END of the string:

result=${string%cut_point*}

For example

string=grog.logs
result=${string%.*}

will return grog

They can also be chained to operate on the same variable in a sequence

No comments:

Post a Comment

With great power comes great responsibility