Monday, October 11, 2010

Linux tip: Bash parameters and parameter expansions

Linux tip: Bash parameters and parameter expansions: "Table 2. Shell expansion pattern matchingExpansion Purpose
${PARAMETER#WORD} The shell expands WORD as in filename expansion and removes the shortest matching pattern, if any, from the beginning of the expanded value of PARAMETER. Using '@' or '$' results in the pattern removal for each parameter in the list.
${PARAMETER##WORD} Results in removal of the longest matching pattern from the beginning rather than the shortest.
${PARAMETER%WORD} The shell expands WORD as in filename expansion and removes the shortest matching pattern, if any, from the end of the expanded value of PARAMETER. Using '@' or '$' results in the pattern removal for each parameter in the list.
${PARAMETER%%WORD} Results in removal of the longest matching pattern from the end rather than the shortest.
${PARAMETER/PATTERN/STRING} The shell expands PATTERN as in filename expansion and replaces the longest matching pattern, if any, in the expanded value of PARAMETER. To match patterns at the beginning of the expanded value of PARAMETER, prefix PATTERN with # or prefix it with % if the match should be done at the end. If STRING is empty, the trailing / may be omitted and the matches are deleted. Using '@' or '$' results in the pattern substitution for each parameter in the list.
${PARAMETER//PATTERN/STRING} Performs the substitution for all matches instead of just the first.

Listing 11 shows some basic usage of the pattern matching expansions.

Listing 11. Pattern matching examples

[ian@pinguino ~]$ x='a1 b1 c2 d2'
[ian@pinguino ~]$ echo ${x#*1}
b1 c2 d2
[ian@pinguino ~]$ echo ${x##*1}
c2 d2
[ian@pinguino ~]$ echo ${x%1*}
a1 b
[ian@pinguino ~]$ echo ${x%%1*}
a
[ian@pinguino ~]$ echo ${x/1/3}
a3 b1 c2 d2
[ian@pinguino ~]$ echo ${x//1/3}
a3 b3 c2 d2
[ian@pinguino ~]$ echo ${x//?1/z3}
z3 z3 c2 d2


- Sent using Google Toolbar"

1 comment:

  1. Very useful!

    It's like sed 's///g' and sed 's///', but more powerful!

    ReplyDelete