将所有文件平铺到一个文件夹中,并删除仅保留同名文件中的一个



大家好,我正在处理这个任务,我必须将当前目录中的所有文件以及其中任何子目录中的所有其他文件平铺成一个级别。然后压缩文件并删除同名的文件。我试着在互联网上搜索,但找不到任何开始,我希望你们能帮助我这个。提前谢谢。

例如:目录a1有5个文件和1个目录

|- a1
| |- j1.jpg
| |-j2.jpg
|- j2.jpg
|- j3.jpg
|- README

输入:比;/one.sh。/handin.zip

预期输出它将创建一个名为handin.zip的文件,其中包含j1.jpg j2.jpg j3.jpg README解压缩.

zip命令具有-j选项,用于存储没有路径的文件。不幸的是,当存在重复的名称时,它将失败,因此您需要预处理文件列表以消除dup。

如果你的路径中没有换行符,那么你可以这样做:

filelist=$(
find . -type f |              # list all the files in the current directory
sed -E 's,(.*/(.*)),2/1,' | # prepend the filename at the start of the path
sort -u -t / -k 1,1 |         # remove duplicate filenames
sed 's,[^/]*/,,'              # strip the filename from the start of the path
)
echo "$filelist" | zip -j handin.zip -@

使用zip -j来清除路径和awk来删除重复的文件名

-j --junk-paths只存储已保存文件的名称(忽略路径),不要存储目录名。默认情况下,zip将存储完整路径(相对于当前目录)。

a[$NF]=$0filename => path/to/file存储到数组中(覆盖重复项)

END{for(i in a)print a[i]}从数组

输出文件列表zip -j handin.zip -@zip filelist from stdin(垃圾路径)

find . -type f|awk -F/ '{a[$NF]=$0}END{for(i in a)print a[i]}'| zip -j handin.zip -@

相关内容

最新更新