Jan 27, 2018

Bash: How to trim/truncate variables / get substrings

In a comment to one of the most useless commands postings was shown how to use the rev command to get the last component of  the path out of a log file:
cat log | grep pattern | rev | cut -d '/' -f 1 | rev
If you only have one variable filled with a path, you can get the last component very easy:
schroff@zerberus:~$ myvar=/ab/cd/ef/gh

schroff@zerberus:~$ echo ${myvar##*\/}
gh
?

## removes the longest matching string for the pattern "*\/" from the beginning (the slash has to be escaped with a backslash).

schroff@zerberus:~$ echo ${myvar#*\/}
ab/cd/ef/gh
# removes the shortest matching pattern. Here only the starting "/"

% and %% removes everything from the end up to the pattern:
schroff@zerberus:~$ echo ${myvar%\/*}
/ab/cd/ef
schroff@zerberus:~$ echo ${myvar%%\/*}
Here the content of the bash manpage:
       ${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.

       ${parameter%word}
       ${parameter%%word}
Remove matching suffix pattern.  The word is expanded to produce a pattern just
as in pathname expansion.  If the pattern matches a  trailing  portion  of  the
expanded  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  mem‐
ber of the array in turn, and the expansion is the resultant list.

No comments:

Post a Comment