简体   繁体   中英

How to eliminate all odd lines from a file but preserve line 1 with a single liner?

I have a series of files with the following structure

Header1
Data2
Garbage3
Data4
Garbage5
Data6

I want to preserve the header(line1) and data(even lines), and throw away the garbage(odd lines except 1). I came about with an ugly solution:

echo $(head -n 1 file.txt) $(awk 'NR%2==0' file.txt) | tr " " "\n" > file.tmp #I cannot rewrite file.txt directly
mv file.tmp file.txt

Is there a way to elegantly do this in a single line?. Note: I don't want to print to the STDOUT, I want to replace file.txt for a clean version of itself?

awk 'NR%2==0||NR==1' odd
Header1
Data2
Data4
Data6

This will print lines based on two conditions:

  1. Line number 1 is printed. OR
  2. Any line which is divisible by 2 is printed.

To make changes in the file:

awk 'NR%2==0||NR==1' odd >odd.tmp && mv odd.tmp odd

Use below command, it will do in-file itself.

sed -ie '1p;1~2d' filename.txt

Example:

$ cat sample.txt
Header1
Data2
Garbage3
Data4
Garbage5
Data6
$
$ sed -ie '1p;1~2d' sample.txt
$
$
$ cat sample.txt
Header1
Data2
Data4
Data6
$

the sed (gnu sed) one-liners should work:

sed -n '1{p;n};p;n' file

OR

sed -n '1p;0~2p' file

with your example, both output:

Header1
Data2
Data4
Data6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM