2

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

0

2 Answers 2

3

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

3
  • sed: unsupported command ~ Commented Aug 21, 2017 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. Commented Aug 21, 2017 at 14:32
  • 2
    Maybe a more idiomatic awk: awk -F\; 'NR%2{$0=$1}1' file Commented Aug 22, 2017 at 2:03
3

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

$ cat ip.txt foo;bar-baz;xyz a;b;c good bad. hi there d;e cool;hot;normal $ sed 's/;.*//;n' ip.txt foo a;b;c good bad. hi there d;e cool 

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

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.