【问题标题】:Using command line to remove lines from text file使用命令行从文本文件中删除行
【发布时间】:2013-10-14 18:38:43
【问题描述】:

我有一个文本文件,需要删除其中不包含http 的所有行。或者,它可以将所有包含http 的文件输出到新文件中。

我的原始文件的名称是list.txt,我需要生成一个新文件,名称类似于new.txt

我知道有几种方法可以通过命令行执行此操作,但我真正要寻找的是最快的方法,因为我需要使用多个文件来执行此操作,并且每个文件的大小都是几 G.. .

【问题讨论】:

  • 这可以用sed或awk或grep和否定运算符来完成,见unix.stackexchange.com/questions/11217/…;真的需要快速吗?这是一个正常的操作,还是一个一次性的任务?
  • 请注意,当您从文件中间删除文本时,您需要使用任何工具重写文件,所以它会很慢(1GB -> 100 秒,如果您的驱动器可以维持 10MB/s,它可能无法做到)

标签: perl shell command-line command


【解决方案1】:

最快、最短的解决方案,

fgrep -v "http"

当然,grep、egrep、awk、perl 等使这更加可替代。

这是一个简短的 shell 脚本。编辑包含的“delhttp.sh”,

#!/bin/bash
if [ $# -eq 0 ] ; then
    fgrep -v "http"
elif [ $# -eq 1 ] ; then
    f1=${1:-"null"}
    if [ ! -f $f1 ]; then echo "file $f1 dne"; exit 1; fi
    fgrep -v "http" $f1 #> $f2
elif [ $# -eq 2 ]; then
    f1=${1:-"null"}
    if [ ! -f $f1 ]; then echo "file $f1 dne"; exit 1; fi
    f2=${2:-"null"}
    fgrep -v "http" $f1 > $f2
fi

然后使用,使这个文件可执行,

chmod +x delhttp.sh

这是一个 perl 脚本(如果你愿意的话),编辑 "delhttp.pl" 包含,

#!/bin/env perl
use strict;
use warnings;
my $f1=$ARGV[0]||"-";
my $f2=$ARGV[1]||"-";
my ($fh, $ofh);
open($fh,"<$f1") or die "file $f1 failed";
open($ofh,">$f2") or die "file $f2 failed";
while(<$fh>) { if( !($_ =~ /http/) ) { print $ofh "$_"; } }

再次,使用,使这个文件可执行,

chmod +x delhttp.pl

【讨论】:

    【解决方案2】:
    perl -i -lne 'print if(/http/)' your_file
    

    如果文件中没有 http 的行,上述命令将从文件中删除所有行。 如果您坚持保留原始文件备份,您可以提供“.bak”选项,如下所述:

    perl -i.bak -lne 'print if(/http/)' your_file
    

    由此将生成your_file.bak,它只是原始文件的副本,原始文件将根据您的需要进行修改。 你也可以使用 awk:

    awk '/http/' your_file
    

    这将输出到控制台。无论如何,您都可以使用 '>' 将输出存储在新文件中。

    【讨论】:

      【解决方案3】:

      你可以使用 grep。使用-v 反转匹配意义,选择不匹配的行。

      grep -v 'http' list.txt
      

      使用 Perl 单行:

      perl -ne '/^(?:(?!http).)*$/ and print' list.txt > new.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-08
        • 2014-01-13
        • 2015-09-07
        • 2011-01-29
        • 1970-01-01
        • 1970-01-01
        • 2015-08-07
        相关资源
        最近更新 更多