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
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 - Thanks for the clarification on the GNU specific sed syntax, and also for the introduction of
1!operator Stephane :)Drav Sloan– Drav Sloan2013-07-30 16:18:33 +00:00Commented 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.)Mike Sherrill 'Cat Recall'– Mike Sherrill 'Cat Recall'2013-07-30 18:50:37 +00:00Commented Jul 30, 2013 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 - 1If 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– Drav Sloan2013-07-30 10:00:16 +00:00Commented Jul 30, 2013 at 10:00 - 1@DravSloan, fairly recent is 2002 here (sed 3.95).Stéphane Chazelas– Stéphane Chazelas2013-07-30 12:11:33 +00:00Commented Jul 30, 2013 at 12:11
Here is awk 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?2015-01-29 12:54:59 +00:00Commented Jan 29, 2015 at 12:54