Sanchit
Sanchit

Reputation: 727

Replace specific line numbers using sed

I use below to replace text on line numbers 29 to 32:

sed -i '29,32 s/^ *#//' file

How can I further add line numbers i.e. line 35 to 38, line 43 & line 45 in above command?

Upvotes: 4

Views: 4980

Answers (2)

potong
potong

Reputation: 58420

This might work for you (GNU sed):

cat <<\! | sed 's:$:s/^ *#//:' | sed -f - -i file
29,32
35,38
43,45
!

Create a here-document with the line ranges you desire and pass these to a sed script that creates another sed script which is run against the desired file.

The here-document could be replaced by a file:

sed 's:$:s/^ *#//:' lineRangeFile | sed -f - -i file

Upvotes: 0

Cyrus
Cyrus

Reputation: 88626

With GNU sed. m is here a label.

sed -i '29,32bm;35,38bm;43bm;45bm;b;:m;s/^ *#//' file

From man sed:

b label: Branch to label; if label is omitted, branch to end of script.

: label: Label for b and t commands.

Upvotes: 5

Related Questions