acbh acbh - 5 months ago 9
Bash Question

Shell string processing using regex and extract words based on delimiters

I have previously asked a question about using regex to get the string from the last colon. I have received some answers though I don't quite know how to integrate it with the rest of the program. I have a command line that will return an output in the form of

st:st:st:st1-st2-st3-st4-...stn
, I want to strip out st1, st2, st3...stn and write them in a text file like
st1 \n "st2 \n...."stn \n
.

I know I can use
while IFS:-
to extract the strings I want but how to get rid of the string before the last colon?

Answer

how to get rid of the string before the last colon?

Use prefix removal:

$ str='st:st:st:st1-st2-st3-st4-...stn'
$ echo "${str##*:}"
st1-st2-st3-st4-...stn

${str##*:} returns the string $str after having removed the longest match that starts from the beginning and ends with a :.

Documentation

From man bash:

${parameter#word}
${parameter##word}
Remove matching prefix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches the beginning of the value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ''#'' case) or the longest matching pattern (the ''##'' case) deleted. If parameter is @ or *, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with @ or *, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.