2014-05-12 43 views
0

我必须写一个unix脚本,我真的不熟悉它,需要帮助。Unix脚本来过滤文件

我有一个根目录,里面我有很多其他的目录。 每个目录包含txt files。 我必须要经过的所有目录和所有文件:

  • 如果文件包含我希望保持 文件短语"file information"

  • 如果文件不包含它,我要删除的文件。

  • 然后,如果一个目录的所有文件都被删除了,并且目录是空的,我想删除这个目录。

我该怎么写这样的脚本?

感谢

+0

尝试什么.. 。? –

+0

哪个命令查找文件或目录?哪个命令在文件中找到单词?什么选项使命令列表文件名称? 'rmdir'命令很嘈杂,但不会删除非空目录。如果按相反顺序对目录列表进行排序,则可以将列表提供给“rmdir”,它将安全地处理所有空目录。你如何重定向标准错误,所以它不会出现? –

回答

0

删除包含 “STRING” 的所有文件:

rm -rf $(find . -type f -exec grep -l 'STRING' {} \;) 

,并删除所有empry目录:

find . -empty -type d -delete 

UPDATE

man grep

-L,--files-不匹配

  Suppress normal output; instead print the name of each input file from which no output would normally have been printed. 
      The scanning will stop on the first match. 

-l,--files与 - 比赛

  Suppress normal output; instead print the name of each input file from which output would normally have been printed. The 
      scanning will stop on the first match. (-l is specified by POSIX.) 
+0

谢谢。 如何删除所有不包含“STRING”的文件? – user1439691

+0

将'-l'选项改为'-L' –

+0

谢谢。找到工作正常,但它不会删除。它写入“非法变量名称”。 也许是因为文件名是try.txt,并找到返回./try.txt? – user1439691