I will forget the variable parameter expansion of bash soon, so I will organize it.
| notation | meaning |
|---|---|
| ${Variable name#pattern} | 最短マッチで、patternに前方一致した部分を取り除く |
| ${Variable name##pattern} | 最長マッチで、patternに前方一致した部分を取り除く |
| ${Variable name%pattern} | 最短マッチで、patternに後方一致した部分を取り除く |
| ${Variable name%%pattern} | 最長マッチで、patternに後方一致した部分を取り除く |
There are many notations other than the above, but for the time being, there are four.
$ {Variable name #Pattern} is a` parameter expansion that removes the part that matches the pattern with the shortest match.
.sh
#!/bin/bash
filepath=/home/name/abc.txt
echo "${filepath#*/}"
home/name/abc.txt
The shortest match is the ** shortest ** string that matches the specified pattern.
| pattern | */ |
|---|---|
| String | /home/name/abc.txt |
| Shortest match | In front of home/ |
| result | home/name/abc.txt |
$ {Variable name #Pattern} is thelongest match, and is aparameter expansion that removes the prefix matching part of the pattern.
.sh
#!/bin/bash
filepath=/home/name/abc.txt
echo "${filepath##*/}"
abc.txt
The longest match refers to the ** longest ** string that matches the specified pattern.
| pattern | */ |
|---|---|
| String | /home/name/abc.txt |
| Longest match | /home/name/ |
| result | abc.txt |
It can be used to get the filename from the file path.
$ {Variable name% pattern} is a parameter expansion that removes the trailing part of the pattern with the shortest match.
.sh
#!/bin/bash
filepath=/home/name/abc.txt
echo "${filepath%/*}"
/home/name
| pattern | /* |
|---|---|
| String | /home/name/abc.txt |
| Shortest match | abc.txt |
| result | /home/name |
It can be used to get the directory of the file path without the filename.
$ {Variable name %% pattern} is a `parameter expansion that removes the part that is the longest match and the trailing part of the pattern.
.sh
#!/bin/bash
filepath=/home/name/abc.txt
echo "${filepath%%/*}"
(None)
| pattern | /* |
|---|---|
| String | /home/name/abc.txt |
| Longest match | /home/name/abc.txt |
| result | (None) |
New Linux textbook
Recommended Posts