bash 循环遍历目录和 zip 中的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39117025/
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
Loop through files in directory and zip
提问by rtho782
I am trying to make a bash script to loop through all files in a directory, and individually zip them to another directory.
我正在尝试制作一个 bash 脚本来遍历目录中的所有文件,并将它们单独压缩到另一个目录。
Currently I have this:
目前我有这个:
FILES=/media/user/storage/unzipped/*
for f in $FILES
do
7za a -t7z /media/user/storage/zipped/$f.7z $f -mx9 -r -ppassword -mhe
done
The problem is that the variable $f includes the absolute path to the source file, so my output file ends up in /media/user/storage/zipped/media/user/storage/unzipped/
问题是变量 $f 包含源文件的绝对路径,所以我的输出文件最终在 /media/user/storage/zipped/media/user/storage/unzipped/
How can I extract only the name from the $f variable?
如何仅从 $f 变量中提取名称?
采纳答案by Mathieu
You can use basename
function:
您可以使用basename
功能:
FILES=/media/user/storage/unzipped/*
for f in $FILES
do
7za a -t7z "/media/user/storage/zipped/$(basename $f).7z" $f -mx9 -r -ppassword -mhe
done
But, you may have problem with files in subfolders, so you can change the wordking directory:
但是,您可能会遇到子文件夹中的文件问题,因此您可以更改 wordking 目录:
#record current dir
OWD=$(pwd)
# move to interesting directory
cd /media/user/storage/unzipped
# zip
for f in *
do
7za a -t7z /media/user/storage/zipped/$f.7z $f -mx9 -r -ppassword -mhe
done
# restore dir
cd $OWD
回答by Martin
You need to extract filename from the path:
您需要从路径中提取文件名:
FILES=/media/user/storage/unzipped/*
for f in $FILES
do
filename=$(basename "$f")
7za a -t7z /media/user/storage/zipped/${filename}.7z $f -mx9 -r -ppassword -mhe
done
回答by Krzysztof W
You can use so called Parameter expansion, which I believe is a good use for you:
您可以使用所谓的Parameter expand,我相信这对您很有用:
FILES=/media/user/storage/unzipped/*
for f in $FILES
do
7za a -t7z /media/user/storage/zipped/${f##*/}.7z $f -mx9 -r -ppassword -mhe
done
More on Parameter Expansion - here
更多关于参数扩展 -这里
回答by sjsam
For recursively finding files in /media/user/storage/unzipped/
you use nullglob
为了递归查找文件,/media/user/storage/unzipped/
请使用 nullglob
shopt -s nullglob
for f in /media/user/storage/unzipped/** # See [1]
do
[ -f "$f" ] && 7za a -t7z "/media/user/storage/zipped/${f##*/}.7z" "$f" -mx9 -r -ppassword -mhe # See [2]
done
shopt -u nullglob
References
参考
- The
**
recursively finds anything under the given directory which may include directories as well, so in the next step check if$f
is indeed a file ([ -f "$f" ]
) and then zip it. - The
${f##*/}
gives you the basename of the file. See param [ expansion ]. - Double quote the variables to prevent [ word splitting ].