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.



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:


sed '1~2d' file


sed '2~2d' file
  • Thanks for the clarification on the GNU specific sed syntax, and also for the introduction of 1! operator Stephane :) – Drav Sloan Jul 30 '13 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.) – Mike Sherrill 'Cat Recall' Jul 30 '13 at 18:50

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
  • 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]. – Drav Sloan Jul 30 '13 at 10:00
  • 1
    @DravSloan, fairly recent is 2002 here (sed 3.95). – Stéphane Chazelas Jul 30 '13 at 12:11

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

sed '0~2d' file

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

  • Hi and welcome to the site! We like answers to be a bit more comprehensive here. Could you edit and include an explanation? – terdon Jan 29 '15 at 12:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.