bash 删除最后/在bash之前的所有内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29761201/
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-18 12:50:50  来源:igfitidea点击:

Delete everything before last / in bash

bashunixsedscripting

提问by Sal

I have many file paths in a file that look like so:

我在一个文件中有很多文件路径,如下所示:

/home/rtz11/files/testfiles/547/prob547455_01

I want to use a bash script that will print all the filenames only to the screen. so basically after the last /. I don't want to assume that it would always be the same length because it might not be. Would there be a way to delete everything before the last /? Maybe a sedcommand? Any help would be greatly appreciated!

我想使用一个 bash 脚本,它只会将所有文件名打印到屏幕上。所以基本上在最后/。我不想假设它总是相同的长度,因为它可能不是。有没有办法删除最后一个之前的所有内容/?也许是sed命令?任何帮助将不胜感激!

回答by Charles Duffy

Using sedfor this is vast overkill -- bash has extensive string manipulation built in, and using this built-in support is far more efficient when operating on only a single line.

使用sed它是一种极大的矫枉过正——bash 内置了大量的字符串操作,当仅在一行上操作时,使用这种内置支持效率更高。

s=/home/rtz11/files/testfiles/547/prob547455_01
basename="${s##*/}"
echo "$basename"

This will remove everything from the beginning of the string greedily matching */. See the bash-hackers wiki entry for parameter expansion.

这将从贪婪匹配的字符串开头删除所有内容*/。有关参数扩展,请参阅bash-hackers wiki 条目



If you only want to remove everything prior tothe last /, but not including it (a literal reading of your question, but also a generally less useful operation), you might instead want if [[ $s = */* ]]; then echo "/${s##*/}"; else echo "$s"; fi.

如果您只想删除最后一个之前的所有内容/,但不包括它(对您的问题的字面解读,但通常也是一个不太有用的操作),您可能想要if [[ $s = */* ]]; then echo "/${s##*/}"; else echo "$s"; fi.

回答by William Pursell

awk '{print $NF}' FS=/ input-file

The 'print $NF' directs awk to print the last field of each line, and assigning FS=/ makes forward slash the field delimeter. In sed, you could do:

'print $NF' 指示 awk 打印每行的最后一个字段,并分配 FS=/ 使字段分隔符正斜杠。在 sed 中,你可以这样做:

sed 's@.*/@@' input-file

which simply deletes everything up to and including the last /.

它只是删除所有内容,包括最后一个/.

回答by unifex

Meandering but simply because I can remember the syntax I use:

蜿蜒但仅仅是因为我记得我使用的语法:

cat file | rev | cut -d/ -f1 | rev

猫文件| 转 | 剪切 -d/ -f1 | 转

Many ways to skin a 'cat'. Ouch.

给“猫”剥皮的方法有很多种。哎哟。