2009-03-05 47 views
11

在目录中,如何删除缺少任何指定字的文件,以便仅保留包含所有字的文件?我试图用grep和rm命令编写一个简单的bash shell脚本,但我迷路了。我完全是新来的Linux,任何帮助,将不胜感激Linux:删除不包含所有指定字的文件

回答

20

如何:

grep -L foo *.txt | xargs rm 
grep -L bar *.txt | xargs rm 

如果一个文件没有,不是包含foo,那么第一行将REM对了。

如果文件不包含bar,然后第二行中删除。

只有同时含有foobar文件应留

-L, --files-without-match 
    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. 

参见@Mykola Golubyev's post在一个循环放置。

+0

我认为带有foo或bar的文件将被删除。 – claf 2009-03-05 13:11:02

+0

不是 - -L否定grep。 – toolkit 2009-03-05 13:14:17

+0

@toolkit:oups,我的坏。 – claf 2009-03-05 13:16:21

0

首先,删除文件列表:

rm flist 

然后,对于每个的话,将文件添加到文件列表中如果包含一个字:

grep -l WORD * >>flist 

然后排序,uniqify并获得数:

sort flist | uniq -c >flist_with_count 

所有这些在flsi文件t_with_count没有单词的数量应该被删除。格式为:

2 file1 
7 file2 
8 file3 
8 file4 

如果有8个单词,那么应该删除file1和file2。我将把脚本的写作/测试留给你。

好吧,你说服了我,这是我的脚本:

#!/bin/bash 
rm -rf flist 
for word in fopen fclose main ; do 
    grep -l ${word} *.c >>flist 
done 
rm $(sort flist | uniq -c | awk '$1 != 3 {print $2} {}') 

这将删除该目录中的文件并没有全部三个词:

-2

这将删除所有文件不包含单词发送

grep -L 'Ping\|Sent' * | xargs rm 
11
list=`Word1 Word2 Word3 Word4 Word5` 
for word in $list 
    grep -L $word *.txt | xargs rm 
done 
5

除了上面的答案:使用换行符作为分隔符来处理与空格的文件名!

grep -L $word $file | xargs -d '\n' rm 
1

要做到同样的匹配文件名(而不是文件的内容,大部分的解决方案上面的),你可以使用以下内容:

for file in `ls --color=never | grep -ve "\(foo\|bar\)"` 
do 
    rm $file 
done 

按照评论:

for file in `ls` 

不该不会被使用。下面的做同样的事情,而不使用ls

for file in * 
do 
    if [ x`echo $file | grep -ve "\(test1\|test3\)"` == x ]; then 
    rm $file 
    fi 
done 

的-ve反转为foo或酒吧在文件名正则表达式模式的搜索。 要添加到列表中的任何其他单词需要用\ \分隔。 例如一个\ | 2路\ |三

0

你可以尝试这样的事情,但它可能会破坏 如果模式包含的grep元字符:

(在这个例子中一二三是模式)

for f in *; do 
    unset cmd 
    for p in one two three; do 
    cmd="fgrep \"$p\" \"$f\" && $cmd" 
    done 
    eval "$cmd" >/dev/null || rm "$f" 
done 
相关问题