bash Bash从长路径中提取文件基名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18845814/
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
Bash extracting file basename from long path
提问by Benoit B.
In bash
I am trying to glob
a list of files from a directory to give as input to a program. However I would also like to give this program the list of filenames
在bash
我试图将glob
目录中的文件列表作为程序的输入。但是我也想给这个程序文件名列表
files="/very/long/path/to/various/files/*.file"
So I could use it like that.
所以我可以这样使用它。
prompt> program -files $files -names $namelist
If the glob
gives me :
如果glob
给我:
/very/long/path/to/various/files/AA.file /very/long/path/to/various/files/BB.file /very/long/path/to/various/files/CC.file /very/long/path/to/various/files/DD.file /very/long/path/to/various/files/ZZ.file
I'd like to get the list of AA BB CC DD ZZ to feed my program without the long pathname and file extension. However I have no clue on how start there ! Any hint much appreciated !
我想获得 AA BB CC DD ZZ 的列表来提供我的程序,而没有长路径名和文件扩展名。但是我不知道如何从那里开始!任何提示非常感谢!
回答by dogbane
It's better to use an array to hold the filenames. A string variable will not handle filenames which contain spaces.
最好使用数组来保存文件名。字符串变量不会处理包含空格的文件名。
Also, you don't need to use the basename
command. Instead use bash's built-in string manipulation.
此外,您不需要使用该basename
命令。而是使用 bash 的内置字符串操作。
Try this:
尝试这个:
files=( /very/long/path/to/various/files/*.file )
for file in "${files[@]}"
do
filename="${file##*/}"
filenameWithoutExtension="${filename%.*}"
echo "$filenameWithoutExtension"
done
回答by epsilon
Solution with basename
for your question
解决basename
您的问题
for file in $files
do
file_name=$(basename $file)
file_name_witout_ext=${file_name%.file}
done
edit (generic way to extract filename without (single) extension)
编辑(提取没有(单个)扩展名的文件名的通用方法)
for file in $files
do
file_name=$(basename $file)
file_name_witout_ext=${file_name%.*}
done
Another thing that can happen is to have filename like "archive.tar.gz". In this case you will have two (or multiple extension). You can then use a more greddy operator
可能发生的另一件事是文件名类似于“archive.tar.gz”。在这种情况下,您将有两个(或多个扩展名)。然后您可以使用更贪婪的运算符
for file in $files
do
file_name=$(basename $file)
file_name_witout_ext=${file_name%%.*}
done
回答by konsolebox
It's simpler like this:
像这样更简单:
files=(/very/long/path/to/various/files/*.file)
names=("${files[@]##*/}") names=("${names[@]%.*}")
progname -files "${files[@]}" -names "${names[@]}"
Or if you could only pass them as a single argument:
或者,如果您只能将它们作为单个参数传递:
progname -files "${files[*]}" -names "${names[*]}"