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

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.

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

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

  • 1
    Is this because the rule is triggered when the result of NR%2 equals 1? – RonJohn Jan 22 '18 at 16:17
  • 1
    @RonJohn, yes. NR%2 = 1 = True that triggers the default action : print – user216043 Jan 22 '18 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. – David Foerster Feb 18 '18 at 12:26
  • @DavidFoerster, Thank you, I completely agree. (my previous comment was oversimplifying the non-zero, non-empty-string ) – user216043 Feb 18 '18 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.