我有一个压缩文件Data.zip
(如果未压缩)包含许多文件:
file_1.txt
file_2.txt
...
...
我想要一个CLI命令将其转换为一个新文件夹Data_zipped
,其中包含Data.zip
未压缩的单个文件:
Data_zipped/file_1.zip
Data_zipped/file_2.zip
...
...
但是诀窍是Data.zip
包含了太多文件(它们总的来说是如此之大),以至于我不能先解压缩Data.zip,然后一口气压缩其中的单个文件:所有这些都必须“实时”进行:
对于中的所有文件 Data.zip/
name_of_that_file.zip
Data_zipped
如何使用CLI做到这一点?
我修改了@George的超级清除脚本,以帮助更好地解释文件夹结构:
#!/bin/bash
#Name of zip file
filename=$1
# Check if valid zip file is passed
if [[ $(file "$filename" | grep -o "Zip archive data") =~ "Zip archive data" ]]
then
# List the contents of the zip file
unzip -l "$filename"
# Get the number of files in zip file
count=$(unzip -l "$filename" | awk '{count = $2 - 2} END {print count}')
echo "$count"
fi
exit 0
当我运行它时,我得到了(我使用一个令牌Data.zip,其中只包含了几个文件,但是您知道了):
./GU_script.sh Data.zip
Archive: Data.zip
Length Date Time Name
--------- ---------- ----- ----
0 2017-11-21 22:58 Data/
120166309 2017-11-21 14:58 Data/Level1_file.csv
120887829 2017-11-21 14:58 Data/Level1_other_file.csv
163772796 2017-11-21 14:59 Data/Level1_yet_other_file.csv
193519556 2017-11-21 14:59 Data/Level1_here_is_another_file.csv
153798779 2017-11-21 14:59 Data/Level1_so_many_files.csv
131918225 2017-11-21 14:59 Data/Level1_many_more_to_go.csv
--------- -------
884063494 7 files
5
因此,基本上,我希望将Level1_file.csv
其他文件和单个文件(-> Level1_file.zip)分别压缩并放入文件夹中。
我最终结合了@George和@David Foerster的答案:
#!/bin/bash
#Name of zip file
filename="$1"
# Check if valid zip file is passed
if file "$filename" | grep -wq "Zip archive data";
then
#!/bin/bash
src="$filename"
dst=.
LC_ALL=C unzip -l "$src" |
sed -re '1,/^-{6}/d; /^-{6}/,$d; /\/$/d; s/^\s*(\S+\s+){3}//' |
while IFS= read -r f; do
out="${f##*/}"; out="$dst/${f%%/*}_zipped/${out%.*}.zip"
if [ ! -d "${out%/*}" ]; then
mkdir -p "${out%/*}" || break
fi
zip --copy "$src" --out "$out" "$f" || break
done
else
echo "Invalid file type: \"zip\" file required"
exit 1
fi
您可以使用的“复制”操作zip(1)
以及一些文件路径处理。它具有将压缩的数据流直接复制到目标存档的优点,而无需进行间歇性的解压缩。
#!/bin/bash
src=Data.zip
dst=.
LC_ALL=C unzip -l "$src" |
sed -re '1,/^-{6}/d; /^-{6}/,$d; /\/$/d; s/^\s*(\S+\s+){3}//' |
while read -r f; do
out="${f##*/}"; out="$dst/${f%%/*}_zipped/${out%.*}.zip"
if [ ! -d "${out%/*}" ]; then
mkdir -p "${out%/*}" || return
fi
zip --copy "$src" --out "$out" "$f" <&- || return
done
我添加LC_ALL=C
了调用,unzip
因为它的输出格式在不同的实现中看起来有些不稳定,并且我至少要避免依赖于语言环境的输出变量。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句