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:
1. awk solution:
2. sed solution:
3. Perl solution:
4. Shell solution:
Do share in the comment section if you know of any other methods!!!
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!!!
No comments:
Post a Comment