2013-03-20 87 views
0

我需要从目录中的大量文本文件中删除包含某些关键字的行。Mass删除包含某些单词的行吗?

例如,我需要所有行被删除他们在这些关键字的任何:为test1,范例4,coding9

这是最接近例子,我想要做的,我可以找到:

sed '/Unix\|Linux/d' *.txt 

注:该行不需要包含所有的关键字被删除,只应该将其删除:)

+0

*质量很低:*你有什么试过?你的代码在哪里? – 2013-03-20 01:31:21

+0

在命令行上?我可以写一个非常简单的Perl脚本来完成这个任务。 : -/ – DataHerder 2013-03-20 01:34:14

+0

Perl对我来说听起来不错,但我发现这样做的唯一方法是使用Notepad ++将所有行加入书签,但由于它覆盖了数千个文件中的数百万行,因此需要很长时间才能完成。 – syf101 2013-03-20 01:35:29

回答

0

看来,你正在寻找一些班轮1命令来读取和写回成千上万文件和数百万行。我不会这样做,因为我宁愿在Perl中编写一个快速而脏的脚本。我非常简短地测试了这个非常简单的文件,它可以工作,但是由于您正在处理数以千计的文件和数百万行,因此我会先测试您在测试目录中写入的任何文件,然后再对其中的一些文件进行验证。

#!/usr/bin/perl 

# the initial directory to read from 
my $directory = 'tmp'; 
opendir (DIR, $directory) or die $!; 

my @keywords = ('woohoo', 'blah'); 

while (my $file = readdir(DIR)) { 

    # ignore files that begin with a period 
    next if ($file =~ m/^\./); 

    # open the file 
    open F, $directory.'/'.$file || die $!; 
    # initialize empty file_lines 
    @file_lines =(); 

    # role through and push the line into the new array if no keywords are found 
    while (<F>) { 
     next if checkForKeyword($_); 
     push @file_lines, $_; 
    } 
    close F; 

    # save in a temporary file for testing 
    # just change these 2 variables to fit your needs 
    $save_directory = $directory.'-save'; 
    $save_file = $file.'-tmp.txt'; 
    if (! -d $save_directory) { 
     `mkdir $save_directory`; 
    } 
    $new_file = $save_directory.'/'.$save_file; 
    open S, ">$new_file" || die $!; 
    print S for @file_lines; 
    close S; 
} 

# role through each keyword and return 1 if found, return '' if not 
sub checkForKeyword() 
{ 
    $line = shift; 
    for (0 .. $#keywords) { 
     $k = $keywords[$_]; 
     if ($line =~ m/$k/) { 
      return 1; 
     } 
    } 
    return ''; 
}