Wednesday, 8 June 2016

Insert new line or text after every n lines in Linux

In one of our earlier articles, we discussed how to insert a line before or after a pattern. In this article, we will see how to insert a line after every n lines in a file.

Let us consider a file. The requirement is to insert a line with text "LINE" afte every 2 lines: 
$ cat file
Unix
Linux
Solaris
AIX
Linux

1awk solution: 
$ awk '1;!(NR%2){print "LINE";}' file
Unix
Linux
LINE
Solaris
AIX
LINE
Linux
'1;' , which means true, prints every line by default. NR, the special variable containing the line number, is checked whether it is a modulus of 2. If so, a line is inserted with the specific text.

 2sed solution: 
$ sed  'N;s/.*/&\nLINE/' file
Unix
Linux
LINE
Solaris
AIX
LINE
Linux
'N' joins every 2 lines. In the joined lines, the newline is inserted at the end of the pattern in the pattern space. 

3Perl solution: 
$ perl -pe 'print "LINE\n" if ($.%2==1 && $.>1);' file
Unix
Linux
LINE
Solaris
AIX
LINE
Linux
The logic is similar to the awk solution. In perl, the $. is the special variable containing the line number. The default printing of every line is done using the 'p' command.

 4Shell solution: 
$ while read line
> do
>  let cnt=cnt+1
>  echo $line
>  [ $cnt -eq 2 ] && { echo "LINE"; cnt=0;}
> done < file 
Unix
Linux
LINE
Solaris
AIX
LINE
Linux
The typical shell script solution. The file contents are read in a while loop. The variable "line" contains the particular record. The line is printed, and the new line to be inserted only when the cnt variable is 2, and then it is reset. 

Do share in the comment section if you know of any other methods!!!

No comments:

Post a Comment