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
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityremove 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
. What Unix are you on? On BSD systems, GNU sed
is sometimes installed as gsed
.
– Kusalananda♦
Aug 21 '17 at 14:32
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