Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reduce number of lines by half with sed [duplicate]

I got a .txt file containing coordinates of points in the format of "x y". They represent a cloud of points on a plane. My idea was to reduce the "density" of the cloud reducing the number of the points by half. I am using linux so to do it i thought to delete half of the lines with sed but just the even or the odd or anyway one line on two. To make it clearer i will post an example:

Before

435.225 108.891
435.212 108.894 <-- to delete
435.225 108.894
435.238 108.894 <-- to delete
435.3 108.894
435.212 108.897 <-- to delete
435.238 108.897
435.288 108.897 <-- to delete

After

435.225 108.891
435.225 108.894
435.3 108.894
435.238 108.897
like image 348
merlinuxxx Avatar asked Jan 18 '26 05:01

merlinuxxx


2 Answers

With sed:

$ sed -n 1~2p file
435.225 108.891
435.225 108.894
435.3 108.894
435.238 108.897

It prints lines whose number is 2K+1, that is, odd ones.

Or deleting the even ones (thanks anishane!):

$ sed 2~2d file
435.225 108.891
435.225 108.894
435.3 108.894
435.238 108.897

From man sed:

Addresses ---> first~step

Match every step'th line starting with line first. For example, ''sed -n 1~2p'' will print all the odd-numbered lines in the input stream, and the address 2~5 will match every fifth line, starting with the second. (This is an extension.)

With awk is just this:

$ awk 'NR%2' file
435.225 108.891
435.225 108.894
435.3 108.894
435.238 108.897

As NR stands for line number, NR%2 will be true just on odd ones, so these will be the ones printed.

like image 194
fedorqui 'SO stop harming' Avatar answered Jan 20 '26 19:01

fedorqui 'SO stop harming'


This might work for you:

sed 'n;d' file

for odd numbers.

And:

sed '1!n;d' file

for even.

like image 40
potong Avatar answered Jan 20 '26 19:01

potong