我正在使用shell变量来调用sed调用。该变量包含文件名为的路径名:
sed "file name is '$variable'"
...
variable=/path/path/file.txt
问题在于我不需要/path/path/
部分。我只需输出file.txt
部分。
我的路径也是动态的所以我猜我需要在某个字符串中搜索(不知何故)从结尾处获得第一个斜杠。我该怎么做?
答案 0 :(得分:2)
您可以使用basename
来执行此操作:
basename /tmp/a.jpg
a.jpg
答案 1 :(得分:1)
您可以使用shell的变量替换功能删除与glob模式匹配的部分:
$ variable=/path/path/file.txt
$ echo ${variable##*/} # Remove longest left part matching "*/"
file.txt
来自bash手册:
${parameter#word} ${parameter##word} 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 match- ing 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} 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 member of the array in turn, and the expansion is the resultant list.