Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell 脚本为找到的每个.txt文件创建单独的zip文件,并在找到后移动它们_Shell_Unix - Fatal编程技术网

Shell 脚本为找到的每个.txt文件创建单独的zip文件,并在找到后移动它们

Shell 脚本为找到的每个.txt文件创建单独的zip文件,并在找到后移动它们,shell,unix,Shell,Unix,我需要一个shell脚本,它基本上可以做到这一点: 在文件夹中搜索所有txt文件,并为找到的每个文件创建一个单独的zip文件,该文件与找到的txt文件+.zip相同 之后,将创建的zip文件移动到txt文件 基本上,它是一个脚本,用一个txt文件列表替换它的zip等效文件,但保持相同的名称 我已使用“查找”来查找要压缩的文件: find . -name '.txt.' -print 结果是: ./InstructionManager.txt.0 ./InstructionManager.t

我需要一个shell脚本,它基本上可以做到这一点:

  • 在文件夹中搜索所有txt文件,并为找到的每个文件创建一个单独的zip文件,该文件与找到的txt文件+.zip相同
  • 之后,将创建的zip文件移动到txt文件
基本上,它是一个脚本,用一个txt文件列表替换它的zip等效文件,但保持相同的名称

我已使用“查找”来查找要压缩的文件:

find . -name '.txt.' -print
结果是:

./InstructionManager.txt.0
./InstructionManager.txt.1
这些是我想要单独压缩的文件(当然它们会更多),但我不知道如何单独使用它们作为参数来生成逗号,如:

zip ./InstructionManager.txt.0.zip ./InstructionManager.txt.0
mv ./InstructionManager.txt.0.zip ./InstructionManager.txt.0
zip ./InstructionManager.txt.1.zip ./InstructionManager.txt.1
mv ./InstructionManager.txt.1.zip ./InstructionManager.txt.1
有什么想法吗?不,我不想要一个包含所有文件的zip:S 感谢您使用find and zip:

find . -name '*.txt.*' -exec zip '{}.zip' '{}' \;
  • 查找
    .txt
    文件
  • 第一个
    -exec
    将压缩文件
  • 第二个
    -exec
    将压缩文件重命名为原始名称
请注意,此过程将覆盖原始文件。为了确保新文件是实际的zip文件,您可以执行以下操作:

file InstructionManager.txt.*
应返回:

InstructionManager.txt.0: Zip archive data, at least v1.0 to extract
InstructionManager.txt.1: Zip archive data, at least v1.0 to extract

使用
find
xargs
,接受带空格的文件名:

find . -name '*.txt.*' -print0 | xargs -0 -r -n1 -I % sh -c '{ zip %.zip %; mv %.zip %;}'

文件被压缩,然后重命名为其原始名称

这是一个带有
find
的单行程序。你试了什么?找到了-名称'.txt.'-print用更多信息编辑了这篇文章。效果很好!:但是现在需要更多的增强。例如,由于文件保持不变,如果脚本再次运行,它将在zip中的zip中创建一个zip。。。。。是否可以使用文件InstructionManager.txt.*命令的输出仅在脚本是真实的txt文件时运行脚本?但是感谢第一个:DOh,还有另一个,如果在这次删除中是这样的话,cd/mnt/usb storage/Logs/&ls-t1/mnt/usb storage/Logs/| tail-n+5 | xargs rm-r zip每个文件都是真实的txt文件,而不是最后5个修改的文件之一?效果很好-压缩文件中还将包含文件夹结构。要简单地压缩上面没有文件夹的文件,请将
-exec
替换为
-execdir
。优雅的解决方案非常有效
find . -name '*.txt.*' -print0 | xargs -0 -r -n1 -I % sh -c '{ zip %.zip %; mv %.zip %;}'