Friday, February 26, 2010

Manipulating Bash Strings

I'm finding myself looking these up quite a lot, so here's a little cheat sheet of the basics.

Using the string "ABCDEFG12345" as an example:

> string="ABCDEFG12345"
> echo $string
ABCDEFG12345

> #Replacement:
> echo ${string/ABC/___}
___DEFG12345

> #Replacement with character class
> echo ${string/[ABC4]/_}
_BCDEFG12345

> #Replace all occurrences:
> echo ${string//[ABC4]/_}
___DEFG123_5

> #Extract from a defined position in the string
> echo ${string:7}
12345
> echo ${string:7:3}
123

> #substring removal (from the front of the string)
> echo ${string#ABC}
DEFG12345
> echo ${string##ABC} #strips the longest substring match
DEFG12345
> string2="abcABCabc123ABCabc
> echo ${string2#a*C}
abc123ABCabc
> echo ${string2##a*C}
abc
> # use the % sign to match from the end
> # % for shortest and %% for longest substring match
> echo ${string%45}
ABCDEFG123

1 comment: