【问题标题】:Mass remove lines that contain certain words?批量删除包含某些单词的行?
【发布时间】:2013-03-20 01:30:11
【问题描述】:

我需要从目录中的大量文本文件列表中删除其中包含某些关键字的所有行。

例如,我需要删除所有包含 any 这些关键字的行:test1、example4、coding9

这是我能找到的最接近我尝试做的例子:

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

注意:这些行不需要包含所有要删除的关键字,只需删除一个即可:)

【问题讨论】:

  • 质量非常低:您尝试过什么?你的代码在哪里?
  • 在命令行上?我可以编写一个非常简单的 Perl 脚本来解决问题。 :-/
  • Perl 对我来说听起来不错,我发现这样做的唯一方法是使用 Notepad++ 为所有行添加书签,但由于这涵盖了数千个文件中的数百万行,这只是花费了太长时间做。
  • 这实际上看起来几乎完美:sed '/test1\|whois\|test2\|test3\|test4\|test5/d' *.txt 但它只是输出终端中的所有行。需要更改哪些文件才能实际编辑文件以删除这些行?

标签: command-line command


【解决方案1】:

您似乎正在寻找一些 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 '';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2014-04-03
    • 2011-09-27
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多