如何编写shell脚本以删除错误目录中的解压缩文件?

时间:2012-01-27 08:01:40

标签: shell

我不小心将文件解压缩到了错误的目录中,实际上有数百个文件......现在该目录与原始文件和错误的解压缩文件搞混了。我想选择解压缩的文件并使用shell脚本删除它们,例如

$unzip foo.zip -d test_dir
$cd target_dir
$ls test_dir | rm -rf

什么都没发生,没有文件被删除,我的命令出了什么问题?谢谢!

7 个答案:

答案 0 :(得分:6)

到目前为止,以下脚本比其他答案有两个主要好处:

  1. 它不需要您将整个第二个副本解压缩到临时目录(我只列出文件名)
  2. 它适用于可能包含空格的文件(解析ls会在空格上中断)

  3. while read -r _ _ _ file; do
      arr+=("$file")
    done < <(unzip -qql foo.zip)
    rm -f "${arr[@]}"
    

答案 1 :(得分:1)

正确的方法是使用xargs:

$find ./test_dir -print | xargs rm -rf

已编辑感谢SiegeX向我解释OP问题。

来自测试目录的“读取”错误文件并将其从目标目录中删除。

$unzip foo.zip -d /path_to/test_dir
$cd target_dir
(cd /path_to/test_dir ; find ./ -type f -print0 ) | xargs -0 rm 

我使用find -0因为文件名可以包含空格和换行符。但如果不是这样,您可以使用ls

运行
$unzip foo.zip -d /path_to/test_dir
$cd target_dir
(cd /path_to/test_dir ; ls ) | xargs rm -rf

在执行之前,您应该通过rm

测试更改echo的脚本

答案 2 :(得分:1)

尝试

 for file in $( unzip -qql FILE.zip | awk '{ print $4 }'); do
     rm -rf DIR/YOU/MESSED/UP/$file
 done

unzip -l列出了有关压缩文件的大量信息。你只需要从中获取文件名。

编辑:使用SiegeX建议的-qql

答案 3 :(得分:0)

这样做:

$ ls test_dir | xargs rm -rf

答案 4 :(得分:0)

您需要ls test_dir | xargs rm -rf作为最后一个命令

为什么:

rm不从stdin获取输入,因此您无法将文件列表传递给它。 xargs获取ls命令的输出并将其显示为rm作为输入,以便它可以删除它。

答案 5 :(得分:0)

压缩前一个。在/ DIR / YOU / MESSED / UP

中运行此命令
unzip -qql FILE.zip | awk '{print "rm -rf  " $4 }' | sh

享受

答案 6 :(得分:0)

以下为我工作(bash)

unzip -l filename.zip | awk '{print $NF}' | xargs rm -Rf
相关问题