I have a text file with some information. How can I write only odd numbered lines from that file to a new file? Using shell script..
2 Answers
You could use sed
:
sed '2~2d' file > new-file
This starts from the second line, matches every 2nd line after that, and deletes the matched lines from the stream. The remaining odd-numbered lines are redirected to a new file.
-
"starts from the second line, matches every 2nd line after that" Wouldn't that be all the even numbers?– RonJohnJan 22, 2018 at 16:06
-
2@RonJohn yes, it matches the even numbered lines and deletes them from the stream, leaving the odd numbered lines intact. We could use
sed '1~2!d'
but why waste a byte?– Zanna ♦Jan 22, 2018 at 16:09 -
2@Zanna but why waste a byte - spoken like a true code-golfer! In fact you could save another byte with
sed 'n;d'
. Jan 22, 2018 at 23:17 -
1@DigitalTrauma for those of us who do not know
sed
:n;d
prints the pattern space (the current line?) and replaces the pattern space with the next line, deletes it immediately, starts the next cycle: gnu.org/software/sed/manual/sed.html#sed-commands-list– jfsJan 23, 2018 at 18:49
awk 'NR%2' file > newFile
NR is the number of the current line; NR%2
= odd line
-
1Is this because the rule is triggered when the result of
NR%2
equals 1?– RonJohnJan 22, 2018 at 16:17 -
1@RonJohn, yes.
NR%2 = 1 = True
that triggers the default action :print
– user216043Jan 22, 2018 at 20:31 -
1@JJoao: Minor nitpick: The Awk language has no real "true" value. Instead, every non-zero number evaluates as true in conditional statements. Feb 18, 2018 at 12:26
-
@DavidFoerster, Thank you, I completely agree. (my previous comment was oversimplifying the non-zero, non-empty-string )– user216043Feb 18, 2018 at 21:54
awk 'NR % 2 == 0' input.file > output.file