Monday, August 27, 2012

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

1. awk 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.

 2. sed 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.

3. Perl 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.

 4. Shell 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!!!

6 comments:

  1. All of your solutions only work if all the lines in the file only contains one word...

    ReplyDelete
  2. What if i want to insert a line after a line containing a specific string. Suppose i want to insert a line 'Hi how r u' after a line containing ' Comment Please' in many text files.

    ReplyDelete
    Replies
    1. awk '1;/Comment Please/{print "Hi How r u";}' file

      Delete
  3. Easier solution: cat file | sed "n;G"

    ReplyDelete
  4. Easier solution:

    cat file | sed "n;G"

    (n prints a line and G is the responsible of printing the other line and the newline)

    ReplyDelete