string 如何在bash中的正斜杠上拆分字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10776679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:29:13  来源:igfitidea点击:

How to split string on forward slash in bash

stringbashsplit

提问by user1306777

example String :

示例字符串:

/gasg/string

/加气/字符串

expected result : string

预期结果 : string

Characters to to remove: all characters between the "/" symbols including the symbols

要删除的字符:“/”符号之间的所有字符,包括符号

回答by Hristo Iliev

With sed:

sed

$ echo "/gasg/string" | sed -e 's/\/.*\///g'
string

With buil-in bash string manipulation:

使用内置的 bash 字符串操作:

$ s="/gag/string"
$ echo "${s##/*/}"
string

Your strings look exactly like Unix pathnames. That's why you could also use the basenameutility - it returnes the last portion of the given Unix pathname:

您的字符串看起来与 Unix 路径名完全一样。这就是为什么您也可以使用该basename实用程序的原因- 它返回给定 Unix 路径名的最后一部分:

$ basename "/gag/string"
string
# It works with relative paths and spaces too:
$ basename "gag/fas das/string bla bla"
string bla bla

回答by Maria Zverina

Also awk - use slash as separator and print last field

还有 awk - 使用斜杠作为分隔符并打印最后一个字段

echo "/gas/string" | awk -F/ '{print $NF}'

Or cut - but that will only work if you have same number of directories to strip

或剪切 - 但这仅在您要删除的目录数量相同时才有效

echo "/gasg/string" |cut -d/ -f 3

回答by pizza

you can use bash string manipulation

您可以使用 bash 字符串操作

a='/gasg/string'
echo ${a##*/}