如何在sh中切断字符串中的已知子字符串?
例如,我有字符串"http://www.myserver.org/very/very/long/path/mystring"
表达式"http://www.myserver.org/very/very/long/path/"
是已知的。我怎么能得到“mystring”?
感谢。
答案 0 :(得分:3)
E.g。使用perl:
echo "http://www.myserver.org/very/very/long/path/mystring" | perl -pe 's|^http://www.myserver.org/very/very/long/path/(.*)$|\1|'
E.g。使用sed:
echo "http://www.myserver.org/very/very/long/path/mystring" | sed 's|^http://www.myserver.org/very/very/long/path/\(.*\)$|\1|'
E.g。当搜索字符串保存在变量中时,此处名为variable
。使用双引号展开变量。
echo "http://www.myserver.org/very/very/long/path/mystring" | sed "s|^${variable}\(.*\)$|\1|"
答案 1 :(得分:1)
在/ bin / dash
下测试$ S="http://www.myserver.org/very/very/long/path/mystring" && echo ${S##*/}
mystring
,其中
S is the variable-name
## remove largest prefix pattern
*/ upto the last slash
进一步阅读,搜索" ##"在man dash
更多插图:
$ S="/mystring/" ; echo ${S##*/}
$ S="/mystring" ; echo ${S##*/}
mystring
$ S="mystring" ; echo ${S##*/}
mystring