bash for 循环多个扩展名并对每个文件做一些事情
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12259331/
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
for loop for multiple extension and do something with each file
提问by devric
I'm trying to write a for loop in bash to get the files with extension of jpg, jpeg, png, this i my attempt, but does not work
我正在尝试在 bash 中编写一个 for 循环来获取扩展名为 jpg、jpeg、png 的文件,这是我的尝试,但不起作用
for file in "${arg}"/*.{jpg,jpeg,png}; do echo ${arg}-something.jpg > z.txt ; done;
basically, i want to get the name of the file with those extension in the current folder, and do something with each file, then output the filename back with a new extension.
基本上,我想获取当前文件夹中具有这些扩展名的文件的名称,并对每个文件执行某些操作,然后使用新的扩展名输出文件名。
回答by choroba
You are not using $fileanywhere. Try
你没有$file在任何地方使用。尝试
for file in "$arg"/*.{jpg,jpeg,png} ; do
echo "$file" > z.txt
done
回答by Nick De Greek
I would like to suggest 2 improvements to the proposed solution:
我想对提议的解决方案提出 2 项改进建议:
A. The for file in "$arg"/.{jpg,jpeg,png} will also produce "$arg"/.jpeg if there are no files with jpeg extention and that creates errors with scripts:
A.如果没有带有 jpeg 扩展名的文件并且会导致脚本出错,则"$arg"/ .{jpg,jpeg,png} 中的 for 文件也会生成 "$arg"/.jpeg:
$ echo *.{jpg,jpeg,png}
myPhoto.jpg *.jpeg *.png
To avoid that, just before the for loop, set the nullglob to remove null globs from from the list:
为了避免这种情况,就在 for 循环之前,设置 nullglob 以从列表中删除 null glob:
$ shopt -s nullglob # Sets nullglob
$ echo *.{jpg,jpeg,png}
myPhoto.jpg
$ shopt -u nullglob # Unsets nullglob
B. If you also want to search *.png or *.PNG or *.PnG (i.e. ignore case), then you need to set the nocaseglob:
B、如果还想搜索*.png or *.PNG or *.PnG(即忽略大小写),则需要设置nocaseglob:
$ shopt -s nullglob # Sets nullglob
$ shopt -s nocaseglob # Sets nocaseglob
$ echo *.{jpg,jpeg,png}
myPhoto.jpg myPhoto.PnG
$ shopt -u nocaseglob # Unsets nocaseglob
$ shopt -u nullglob # Unsets nullglob

