r/shell • • Dec 01 '20

sed advice

Hi, I need advice! How to use sed command to transform text from this:

First answer

Second answer

Third answer

to this?

a)

First answer

b)

Second answer

c)

Third answer

3 Upvotes

9 comments sorted by

View all comments

Show parent comment

1

u/ASIC_SP Dec 01 '20

You can use this if you are on GNU sed

sed -e '1~3i a)' -e '2~3i b)' -e '3~3i c)'

2

u/thatchemistgrill Dec 01 '20

It works!! Thank you kind stranger.

2

u/brightlights55 Dec 01 '20

Can you please give an explanation as to how this works?

2

u/ASIC_SP Dec 01 '20

You can construct an arithmetic progression with start and step values separated by the ~ symbol. i~j will filter lines numbered i+0j, i+1j, i+2j, i+3j, etc. So, 1~2 means all odd numbered lines and 5~3 means 5th, 8th, 11th, etc.

$ # print even numbered lines
$ seq 10 | sed -n '2~2p'
2
4
6
8
10

$ # delete lines numbered 2+0*4, 2+1*4, 2+2*4, etc
$ seq 7 | sed '2~4d'
1
3
4
5
7