1

I need to prepend a line counter to lines matching specific patterns in a file, while still outputting the lines that do not match this pattern.

For example, if my file looks like this:

aaa 123
bbb 456
aaa 666
ccc 777
bbb 999

and the patterns I want to count are 'aaa' and 'ccc', I'd like to get the following output:

1:aaa 123
bbb 456
2:aaa 666
3:ccc 777
bbb 999

Preferably I'm looking for a Linux one-liner. Shell or tool doesn't matter as long it's installed by default in most distros.

4

2 回答 2

2

使用以下代码。以下方法在perl中

open FH,"<abc.txt";

$incremental_val = 1;

while(my $line = <FH>){
  chomp($line);

  if($line =~ m/^aaa / || $line =~ m/^ccc /){
    print "$incremental_val : $line\n";
    $incremental_val++;
    next;
  }
  print "$line\n";
}

close FH;

输出将如下所示。

1 : aaa 123
bbb 456
2 : aaa 666
3 : ccc 777
bbb 999
于 2013-07-01T09:04:40.093 回答
2

awk

awk '{if ($1=="aaa" || $1=="ccc") {a++; $0=a":"$0}} {print}' file
1: aaa 123
bbb 456
2: aaa 666
3: ccc 777
bbb 999

解释

循环检查第一个字段是否为aaa或的行ccc。如果是这样,请将行 ( $0) 附加到变量a并自动递增它。最后,在所有情况下打印该行:如果匹配的模式将a在开头具有,否则只是原始行。

于 2013-07-01T09:09:39.097 回答