4

All I need is the sed or awk code to remove the even numbered lines in a text file. Nothing fancy I just need to remove irrelevant data on the even lines of a text file.

4 Answers 4

6

Simply:

sed 'n;d' file 

for even lines, and

sed '1!n;d' file 

for odd lines.

With the GNU implementation of sed, you can also use this syntax:

Odd:

sed '1~2d' file 

Even:

sed '2~2d' file 
2
  • Thanks for the clarification on the GNU specific sed syntax, and also for the introduction of 1! operator Stephane :) Commented Jul 30, 2013 at 16:18
  • "1" is an address restriction. I think the "!" operator here inverts the "n". (Don't go to the next line; delete this one.) Commented Jul 30, 2013 at 18:50
2

You can remove said lines of unwanted text by like so

sed -i '/[REGEX]/d' <FILE> 

Where [REGEX] is a regular expression that matches the unwanted line of text, and <FILE> is the name of the file you want to remove the text from. You can nest delete (//d) commands like so:

sed '/[REGEX]/d ; /[REGEX]/d ; /[REGEX]/d' 

Here's an example:

echo "a" > file ; echo "abcd" >> file sed -i '/^a$/d' file cat file # => abcd 

If your version of sed doesn't support the -i option, you can use to following to the same effect.

cat file | sed '/[REGEX]/d' > file_2 && cat file_2 > file && rm file_2 



A word to the wise

Redirecting the output of cat file right back into file will not have the desired effect. It will in fact, truncate file completely, that is it will completely erase file.

So don't do this:

cat file | sed '/[REGEX]/d' > file 
2
  • 1
    If you use a fairly recent GNU sed you can avoid the redirect, cat and rm with sed -i '/[REGEX]/d' file. That solution also relies on the even lines matching [REGEX]. Commented Jul 30, 2013 at 10:00
  • 1
    @DravSloan, fairly recent is 2002 here (sed 3.95). Commented Jul 30, 2013 at 12:11
0

Here is solution:

For deleting odd line:

awk 'NR%2==0{ print $0 > "infile" }' infile 

For deleting even lines:

awk 'NR%2{ print $0 > "infile" }' infile 

Note that above commands deletes the related lines in-place from infile input file, so be careful you write the output in to the same input file.

You can write them into another separate file like as following:

This will create the EvenLines file contain even-number of lines:

awk 'NR%2==0{ print $0 > "EvenLines" }' infile 

And this one will create the OddLines file contain odd-number of lines:

awk 'NR%2{ print $0 > "OddLines" }' infile 
-1

sed '0~2d' file 

This command is used to delete the even lines in the files.

1
  • Hi and welcome to the site! We like answers to be a bit more comprehensive here. Could you edit and include an explanation? Commented Jan 29, 2015 at 12:54

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.