Home > bash > Bash – Pattern matching operators

Bash – Pattern matching operators

${variable#pattern} – If the pattern matches the beginning of the variable’s value, delete the shortest part that matches and return the rest.

user@computer:~/scripts$ path="/home/user/scripts"
user@computer:~/scripts$ echo ${path#/*/}
user/scripts

${variable##pattern} – If the pattern matches the beginning of the variable’s value, delete the longest part that matches and return the rest.

user@computer:~/scripts$ path="/home/user/scripts"
user@computer:~/scripts$ echo ${path##/*/}
scripts

${variable%pattern} – If the pattern matches the end of the variable’s value, delete the shortest part that matches and return the rest.

user@computer:~/scripts$ path="/home/user/scripts/very.big.file"
user@computer:~/scripts$ echo ${path%.*}
/home/user/scripts/very.big

${variable%%pattern} – If the pattern matches the end of the variable’s value, delete the longest part that matches and return the rest.

user@computer:~/scripts$ path="/home/user/scripts/very.big.file"
user@computer:~/scripts$ echo ${path%%.*}
/home/user/scripts/very

${variable/pattern/string} or ${variable//pattern/string} – The longest match to pattern in variable is replaced by string. In the first form, only the first match is replaced. In the second form, all matches are replaced. If the pattern begins with a #, it must match at the start of the variable. If it begins with a %, it must match with the end of the variable. If string is null, the matches are deleted. If variable is @ or *, the operation is applied to each positional parameter in turn and the expansion is the resultant list.

user@computer:~$_date="2011-04-13"
user@computer:~$echo ${_date/-/_}
2011_04-13
user@computer:~$echo ${_date//-/_}
2011_04_13

source: “Learning the bash Shell, Third Edition, by Cameron Newham and Bill Rosenblatt. Copyright 2005 O’Reilly Media, Inc., ISBN 0-596-00965-8.”

Advertisements
Categories: bash Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: