Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove odd or even lines from a text file

Tags:

linux

sed

awk

I need to remove odd lines in a text file to make a down-sampling. I've found this command,

awk 'NR%2==0' file 

but it only prints the odd lines in the terminal. How to really remove them?

I don't really care for even or odd, I want them removed from the file or printed in another file. This only prints them in the terminal.

like image 964
SamuelNLP Avatar asked Jan 23 '14 13:01

SamuelNLP


People also ask

How do you remove even lines in Notepad ++?

Open the replace menu, fill in ([^\n]*\n)[^\n]*\n in the "Find what" box and $1 in the "Replace with" box. Then select regular expression for the search mode, click replace all and every second line is deleted. You can build similar regexes if you want to do something similar.

How do I remove a line from a file?

Deleting line using sed To delete a line, we'll use the sed “d” command. Note that you have to declare which line to delete. Otherwise, sed will delete all the lines.


2 Answers

awk

The % is a modulus operator and NR is the current line number, so NR%2==0 is true only for even lines and will invoke the default rule for them ({ print $0 }). Thus to save only the even lines, redirect the output from awk to a new file:

awk 'NR%2==0' infile > outfile 

sed

You can accomplish the same thing with sed. devnulls answer shows how to do it with GNU sed. Below are alternatives for versions of sed that do not have the ~ operator:

keep odd lines

sed 'n; d' infile > outfile 

keep even lines

sed '1d; n; d' infile > outfile 
like image 165
Thor Avatar answered Sep 20 '22 04:09

Thor


Using GNU sed:

sed -i '0~2d' filename 

to remove the even numbered lines from the file.

For removing odd numbered lines:

sed -i '1~2d' filename 

The -i option would cause the changes to be saved to the file in-place.

Quoting from the manual:

`FIRST~STEP'      This GNU extension matches every STEPth line starting with line      FIRST.  In particular, lines will be selected when there exists a      non-negative N such that the current line-number equals FIRST + (N      * STEP).  Thus, to select the odd-numbered lines, one would use      `1~2'; to pick every third line starting with the second, `2~3'      would be used; to pick every fifth line starting with the tenth,      use `10~5'; and `50~0' is just an obscure way of saying `50'. 
like image 27
devnull Avatar answered Sep 19 '22 04:09

devnull