Wednesday, February 6, 2013

How to delete every nth line in a file in Linux?



How to delete or remove every nth line in a file? The requirement is to remove every 3rd line in the file.

Let us consider a file with the below content.
$ cat file
AIX
Solaris
Unix
Linux
HPUX

1. awk solution :
$ awk 'NR%3' file
AIX
Solaris
Linux
HPUX
   NR%3 will be true for any line number which is not multiple of 3, and hence the line numbers which are multiple's of 3 does not get printed.
Note: NR%3 is same as NR%3!=0

2. Perl:
$ perl -lne 'print if $.%3 ;' file
AIX
Solaris
Linux
HPUX
  Same logic as awk solution. $. in perl contains the line number of the file.

3. sed:
$ sed 'n;n;d;' file
AIX
Solaris
Linux
HPUX
  n commands prints the current line and reads the next line. Hence 2 consecutive n's result in 2 lines getting printed with the 3rd line in the pattern space. d command deletes the line(3rd line) which is present in the pattern space. And this continues till the end of the file.

4. Bash Shell script:
$ x=0
$ while read line
> do
>   ((x++))
>   [ $x -eq 3 ] && { x=0; continue; }
>   echo $line
> done < file
AIX
Solaris
Linux
HPUX
  A simple logic of incrementing a variable by 1 after every line is processed. When the count becomes 3, the particular line is not printed and the counter is reset.
Related Posts Plugin for WordPress, Blogger...

No comments:

Post a Comment