String manipulation
How to modify strings from a variable in bash without losing your sanity
[gamma:~] s=1234
# only remove from the beggining of the string
[gamma:~] echo ${s#2}
1234
[gamma:~] echo ${s#12}
34
[gamma:~] echo ${s#34}
1234
% ony remove from the end of the string
[gamma:~] echo ${s%34}
12
to remove substrings from anywhere inside the string
[gamma:~] echo ${s/23/}
14
String extraction
you can also use regexps. With a bit of care, tough. For example, say you have
this string:
artist:"Veruca Salt" title:"Best You Can Get" album:"Resolver", and you want
to extract, say, the album field. The idea for the regexp would be: match
anything that starts with album:, then has a ", then stuff that isn't ",
and then a final ". You'll need something like the following
[gamma:~] expr match 'artist:"Veruca Salt" title:"Best You Can Get" album:"Resolver"' '.*album:"\([^"]\+\)"'
Resolver
Why the .*? because expr implicitly adds a ^ in front of each regexp it
receives. FSM only knows why.
Why the \( \)? because by default, expr only returns the length of the match. Look
[gamma:~] expr match 'artist:"Veruca Salt" title:"Best You Can Get" album:"Resolver"' '.*artist:"[^"]\+"'
20
the parentheses, if present, tell to expr to return the part of the match surrounded by them
[gamma:~] expr match 'artist:"Veruca Salt" title:"Best You Can Get" album:"Resolver"' '.*artist:"\([^"]\+\)"'
Veruca Salt