remove all text after a certain character that appears on all odd lines

this works for every line in the file with sed

sed 's/;.*//' 

how to edit this sed line so it just does all odd lines


With GNU sed:

$ sed '1~2s/;.*//' file

The address range 1~2 will match line 1, and then every second line after that. The general case is first~step and the example in the manual is sed -n 1~2p which will print all odd lines.

This is a GNU extension.

The equivalent thing in awk:

$ awk 'NR % 2 { sub(";.*", "") } { print }' file

Or, as suggested by Arrow in comments:

$ awk -F';' 'NR % 2 { $0 = $1 } { print }' file

which has the same effect, but instead of explicitly substituting out everything after the first ; it uses ; as the field separator (with -F';') and then outputs only the first field (by replacing the whole input line with only the first field for odd rows).

  • sed: unsupported command ~
    – bob
    Aug 21 '17 at 14:32
  • @bob Which means that you are not using GNU sed. What Unix are you on? On BSD systems, GNU sed is sometimes installed as gsed.
    – Kusalananda
    Aug 21 '17 at 14:32
  • 2
    Maybe a more idiomatic awk: awk -F\; 'NR%2{$0=$1}1' file
    – IsaaC
    Aug 22 '17 at 2:03

This probably might work with all sed version, tested on GNU sed though

$ cat ip.txt 
good bad. hi there

$ sed 's/;.*//;n' ip.txt 
good bad. hi there

The n command will fetch next line but won't change anything, effectively allowing to change only odd lines

With perl

perl -pe 's/;.*// if $.%2' ip.txt

where if $.%2 adds condition to perform substitution only if line number is odd

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.