如何从 shell 字符串中删除最后一个字段

发布于 2024-10-09 21:33:46 字数 161 浏览 0 评论 0原文

如何剪切此 shell 字符串中的最后一个字段

LINE="/string/to/cut.txt"

,使字符串看起来像这样

LINE="/string/to/"

提前致谢!

How to cut the last field in this shell string

LINE="/string/to/cut.txt"

So that the string would look like this

LINE="/string/to/"

Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

忱杏 2024-10-16 21:33:46

就其价值而言,基于 cut 的解决方案:

NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"

For what it's worth, a cut-based solution:

NEW_LINE="`echo "$LINE" | rev | cut -d/ -f2- | rev`/"
马蹄踏│碎落叶 2024-10-16 21:33:46

我认为你可以使用“dirname”命令。它接受输入文件路径,删除文件名部分并返回路径。例如:

$ dirname "/string/to/cut.txt"
/string/to

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 "/string/to/cut.txt"
/string/to
残月升风 2024-10-16 21:33:46

这将适用于现代 Bourne 版本,例如 Dash、BusyBox ash 等,以及后代,例如 Bash、Korn shell 和 Z shell。

LINE="/string/to/cut.txt"
LINE=${LINE%/*}

或保留最后的斜杠:

LINE=${LINE%/*}/

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.

LINE="/string/to/cut.txt"
LINE=${LINE%/*}

or to keep the final slash:

LINE=${LINE%/*}/
萌︼了一个春 2024-10-16 21:33:46
echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'
echo "/string/to/cut.txt" | awk -F'/' '{for (i=1; i<NF; i++) printf("%s/", $i)}'
五里雾 2024-10-16 21:33:46

回显 $LINE | grep -o '.*/' 也有效。

echo $LINE | grep -o '.*/' works too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文