如何剪切最后一个 '/' 后的所有字符?
本文
xxxx/x/xx/xx/xxxx/x/yyyyy
xxx/xxxx/xxxxx/yyy
应该返回
xxxx/x/xx/xx/xxxx/x
xxx/xxxx/xxxxx
答案1
如果你想得到“切割部分”
yyy
yyyyy
您可以使用
sed 's|.*/||'
例如。
echo "xxx/xxxx/xxxxx/yyy" | sed 's|.*/||'
echo "xxxx/x/xx/xx/xxxx/x/yyyyy" | sed 's|.*\/||'
输出
yyy
yyyyy
(注意:这利用了 sed 在 s 命令中使用 / 以外的分隔符的能力,在本例中为 |)
如果你想获取字符串的开头:
xxx/xxxx/xxxxx
xxxx/x/xx/xx/xxxx/x
您可以使用
sed 's|\(.*\)/.*|\1|'
例如。
echo "xxx/xxxx/xxxxx/yyy" | sed 's|\(.*\)/.*|\1|'
echo "xxxx/x/xx/xx/xxxx/x/yyyyy" | sed 's|\(.*\)/.*|\1|'
输出
xxx/xxxx/xxxxx
xxxx/x/xx/xx/xxxx/x
答案2
参数扩展bash
bash
在这种情况下,您可以使用参数扩展
${parameter%word}
哪里word
/*
${parameter##word}
哪里word
*/
例子:
删除最后一部分
$ asdf="xxx/xxxx/xxxxx/yyy"
$ echo ${asdf%/*}
xxx/xxxx/xxxxx
描述如下man bash
:
${parameter%word}
${parameter%%word}
Remove matching suffix pattern. 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 posi‐
tional 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.
删除除最后一部分以外的所有内容
$ asdf="xxx/xxxx/xxxxx/yyy"
$ echo ${asdf##*/}
yyy
您可以像这样添加斜线
$ echo /${asdf##*/}
/yyy
根据编辑的问题,在某一特定情况下准确获得您想要的内容。但此后这个问题已被几个人编辑过,现在很难知道您想要什么。
描述如下man bash
:
${parameter#word}
${parameter##word}
Remove matching prefix pattern. 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
matching pattern (the ``#'' case) or the longest matching pat‐
tern (the ``##'' case) deleted. If parameter is @ or *, the
pattern removal operation is applied to each positional parame‐
ter in turn, and the expansion is the resultant list. If param‐
eter 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.
答案3
如果你正在切割离开琴弦的末端,dirname
可能符合要求:
$ dirname xxxx/x/xx/xx/xxxx/x/yyyyy
xxxx/x/xx/xx/xxxx/x
$ _
如果您尝试隔离字符串的最后一部分,请使用echo /$(basename "$str")
。
$ str=xxxx/x/xx/xx/xxxx/x/yyyyy
$ echo /$(basename "$str")
/yyyyy
$ _
答案4
另一种方法是grep
仅显示每行的最后一个斜线及其后面的内容:
$ grep -o '/[^/]*$' example.txt
/yyy
/yyyyy
解释:
-o
告诉grep
仅显示行的匹配部分而不是整行。
此模式/[^/]*$
匹配一个文字斜杠,/
后跟除斜杠之外的任意字符,匹配[^/]
任意次,*
直到行尾$
。