Home > awk, Interesting, sed > Delete specific line numbers in a file – awk, sed

Delete specific line numbers in a file – awk, sed

Problem:
You want to delete certain lines in a file. Say 3,6,9,12 etc.

$ less file
first
second
third
fourth
fifth
sixth
seventh
eigth
nineth
tenth

Solution:
1. Using awk.

$ awk 'NR%3' file
first
second
fourth
fifth
seventh
eigth
tenth

My understanding of how it works.

$ man awk

NR The total number of input records seen so far.

$ awk 'NR' file 

Will print all the rows as NR returns a value which equates to true and thus gets printed.
If you want to only print the x row

$ awk 'NR == 2' file
second
$ awk 'NR == 5' file
fifth

The below example prints nothing. It is like saying print but the result is false so nothing gets printed.

$ awk '0' file

So what happens with NR%3 is that anything that is not 0 gets printed.
1%3 result is 1 it gets printed.
2%3 result is 2 it gets printed.
3%3 result is 0 it does not get printed.
4%3 result is 1 it gets printed.
and so on.

2. Using sed.

$ sed 'n;n;d' file
first
second
fourth
fifth
seventh
eigth
tenth

How I think it works.

$ sed 'n;n;d' file

n – move to the next line
n – move to the next line
d – delete that line.

I think that due to d repeating the next cycle, since we still have lines in the file, it starts over and repeats the same till EOF.

$ info sed

`n’
If auto-print is not disabled, print the pattern space, then,
regardless, replace the pattern space with the next line of input.
If there is no more input then `sed’ exits without processing any
more commands.

`d’
Delete the pattern space; immediately start next cycle.

NB: File must not contain blank lines.

Source:
http://www.unix.com/shell-programming-scripting/245088-how-delete-line-number-3-6-9-12-15-so.html

Advertisements
Categories: awk, Interesting, sed Tags:
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: