string 如何从shell字符串中剪切最后一个字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4563060/
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
How to cut the last field from a shell string
提问by user558134
How to cut the last field in this shell string
如何剪切此 shell 字符串中的最后一个字段
LINE="/string/to/cut.txt"
So that the string would look like this
所以字符串看起来像这样
LINE="/string/to/"
Thanks in advance!
提前致谢!
采纳答案by user554272
I think you could use the "dirname" command. It takes in input a file path, removes the filename part and returns the path. For example:
我认为您可以使用“dirname”命令。它接受输入文件路径,删除文件名部分并返回路径。例如:
$ dirname "/string/to/cut.txt"
/string/to
回答by Lucas Jones
For what it's worth, a cut
-based solution:
对于它的价值,cut
基于 - 的解决方案:
NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"
回答by Paused until further notice.
This will work in modern Bourne versions such as Dash, BusyBox ash, etc., as well as descendents such as Bash, Korn shell and Z shell.
这将适用于现代 Bourne 版本,例如 Dash、BusyBox ash 等,以及 Bash、Korn shell 和 Z shell 等后代。
LINE="/string/to/cut.txt"
LINE=${LINE%/*}
or to keep the final slash:
或保留最后的斜线:
LINE=${LINE%/*}/
回答by ajreal
echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'
回答by mohit6up
echo $LINE | grep -o '.*/'
works too.
echo $LINE | grep -o '.*/'
也有效。