Add a blank line between lines from different groups

I have a Aform file (frequency, file name, line of code):

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 need a conclusion Blike:

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 Acontains the file name and lines of code from the file, and the first field is the frequency, i.e. the number of lines of code in the file.

I have to go through these lines of code files. I find this tedious, and it would be easier for me if there was a line break between the inputs of different files, hence the desired result.

+3
source share
4 answers

Awk can do this:

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

A is the name of the file.

+6
source

You can use awk:

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

Quick and dirty Perl for you:

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

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

0
source

To add GNU sed to awk and Perl solutions:

$ 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

Explanations:

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
0
source

Source: https://habr.com/ru/post/1779031/


All Articles