1

如何在每个 grep 结果后添加一个空行?

例如, grep -o "xyz" 可能会给出类似 -

file1:xyz
file2:xyz
file2:xyz2
file3:xyz

我希望输出是这样的 -

file1:xyz

file2:xyz
file2:xyz2

file3:xyz

我想做类似的事情

grep "xyz" | perl (code to add a new line after every grep result)
4

4 回答 4

3

这是您问题的直接答案:

 grep 'xyz' | perl -pe 's/$/\n/'

但这更好:

 perl -ne 'print "$_\n" if /xyz/'

编辑

好的,在你编辑之后,你(几乎)想要这个:

grep 'xyz' * | perl -pe 'print "\n" if /^([^:]+):/ && ! $seen{$1}++'

如果您不喜欢开头的空行,请使其:

grep 'xyz' * | perl -pe 'print "\n" if /^([^:]+):/ && ! $seen{$1}++ && $. > 1'

注意:这不适用于带有冒号的文件名。:) ½

于 2013-07-23T16:57:54.097 回答
1

If you want to use perl, you could do something like

grep "xyz" | perl -p -e 's/(.*)/\1\n/g'

If you want to use sed (where I seem to have gotten better results), you could do something like

grep "xyz" | sed 's/.*/\0\n/g'
于 2013-07-23T16:23:45.273 回答
1

这会在 grep 输出的每一行之后打印一个换行符:

grep "xyz" | perl -pe 'print "\n"'

这会在不同文件的结果之间打印一个换行符。(在阅读时回答问题。)

grep 'xyx' * | perl -pe '/(.*?):/; if ($f ne $1) {print "\n"; $f=$1}'
于 2013-07-23T16:16:13.417 回答
0

使用状态机确定何时打印空行:

#!/usr/bin/env perl

use strict;
use warnings;

# state variable to determine when to print a blank line
my $prev_file = '';

# change DATA to the appropriate input file handle
while( my $line = <DATA> ){

  # did the state change?
  if( my ( $file ) = $line =~ m{ \A ([^:]*) \: .*? xyz }msx ){

    # blank lines between states
    print "\n" if $file ne $prev_file && length $prev_file;

    # set the new state
    $prev_file = $file;
  }

  # print every line
  print $line;
}

__DATA__
file1:xyz
file2:xyz
file2:xyz2
file3:xyz
于 2013-07-23T17:02:54.743 回答