Add blank line between lines from different groups

拈花ヽ惹草 提交于 2019-12-18 08:58:28

问题


I have a file A of the form (frequency,file name,code lines):

1 file_name1 code_line1
2 file_name2 code_line2
2 file_name2 code_line3
2 file_name3 code_line4
2 file_name3 code_line5
3 file_name4 code_line6
3 file_name4 code_line7
3 file_name4 code_line8

I want output B as:

1 file_name1 code_line1

2 file_name2 code_line2
2 file_name2 code_line3

2 file_name3 code_line4
2 file_name3 code_line5

3 file_name4 code_line6
3 file_name4 code_line7
3 file_name4 code_line8

Basically the file A contains file name and code lines from the file and the first field is the frequency, i.e., number of code lines in the file.

I am supposed to go through these code lines file wise. I am finding it tedious and it would be easier for me if there was a line gap between entries of different files, hence the desired output.


回答1:


Awk could do it:

awk '{if(NR > 1 && $2 != prev_two){printf "\n";} prev_two=$2; print $0}' A

A being the file name.




回答2:


You can use Awk:

awk 'BEGIN{file=0}{if (file && file!=$2) {print ""} print $0; file=$2}' fileA



回答3:


Quick and dirty Perl for you:

$lastfile = '';
while (<>) {
  @line = split(/\s+/);
  $filename = $line[1];
  print "\n" unless ($lastfile eq $filename);
  $lastfile = $filename;
  print;
}

Usage: perl script.pl < original_file.txt > newfile.txt




回答4:


To add to the awk and Perl solutions, a GNU sed solution:

$ sed -r 'N;/file_name(\w+).*\n.*file_name\1/!{s/\n/&\n/;P;s/^[^\n]*\n//};P;D' infile
1 file_name1 code_line1

2 file_name2 code_line2
2 file_name2 code_line3

2 file_name3 code_line4
2 file_name3 code_line5

3 file_name4 code_line6
3 file_name4 code_line7
3 file_name4 code_line8

Explained:

N # Append next line to pattern space

# If the numbers after the 'file_name' string DON'T match, then
/file_name(\w+).*\n.*file_name\1/! {
    s/\n/&\n/      # Insert extra newline
    P              # Print up to first newline
    s/^[^\n]*\n//  # Remove first line in pattern space
}
P # Print up to newline - if we added the extra newline, this prints the empty line
D # Delete up to newline, start new cycle


来源:https://stackoverflow.com/questions/4380447/add-blank-line-between-lines-from-different-groups

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!