7

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..

1

2 Answers 2

12

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.

4
  • "starts from the second line, matches every 2nd line after that" Wouldn't that be all the even numbers?
    – RonJohn
    Jan 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
    – jfs
    Jan 23, 2018 at 18:49
9
awk 'NR%2' file > newFile

NR is the number of the current line; NR%2 = odd line

4
  • 1
    Is this because the rule is triggered when the result of NR%2 equals 1?
    – RonJohn
    Jan 22, 2018 at 16:17
  • 1
    @RonJohn, yes. NR%2 = 1 = True that triggers the default action : print
    – user216043
    Jan 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 )
    – user216043
    Feb 18, 2018 at 21:54

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .