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 LinuxThe 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 LinuxThe 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!!!
All of your solutions only work if all the lines in the file only contains one word...
ReplyDeleteNot really. Can you please show how?
DeleteWhat 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.
ReplyDeleteawk '1;/Comment Please/{print "Hi How r u";}' file
DeleteEasier solution: cat file | sed "n;G"
ReplyDeleteEasier solution:
ReplyDeletecat file | sed "n;G"
(n prints a line and G is the responsible of printing the other line and the newline)