Pattern Matching
There are two kinds of pattern matching available: matching from the left and matching from the right. The operators, with their functions and an example, are shown in the following table:
Operator |
Function |
Example |
${foo#t*is} |
Deletes the shortest possible match from the left |
export $foo="this is a test" echo ${foo#t*is} is a test |
${foo##t*is} |
Deletes the longest possible match from the left |
export $foo="this is a test" echo ${foo##t*is} a test |
${foo%t*st} |
Deletes the shortest possible match from the right |
export $foo="this is a test" echo ${foo%t*st} this is a |
${foo%%t*st} |
Deletes the longest possible match from the right |
export $foo="this is a test" echo ${foo%%t*is} |
NOTE
While the # and % identifiers may not seem obvious, they have a convenient mnemonic. The # key is on the left side of the $ key on the keyboard and operates from the left. The % key is on the right of the $ key and operated from the right.
These operators can be used to do a variety of things. For example, the following script changes the extension of all .html files to .htm.
#!/bin/bash # quickly convert html filenames for use on a dossy system # only handles file extensions, not filenames for i in *.html; do if [ -f ${i%l} ]; then echo ${i%l} already exists else mv $i ${i%l} fi done