Justpee
Justpee

Reputation: 191

How to search and replace the specific line number string

line_index="2d";

file="./Desktop/books.sh";

sed -i.bak -e $line_index $file

Will delete the entire line that $line_index is pointing to

sed -i "s/harry/potter/g" $file

will search for harry and replace with potter

Is there anyway that i can combine both statement so it will only replace the specific line number of harry instead of all the harry in the file.

Upvotes: 1

Views: 820

Answers (2)

SLePort
SLePort

Reputation: 15461

To restrict substitution to a line number, add it before the command:

sed -i "2s/harry/potter/" $file

Upvotes: 1

choroba
choroba

Reputation: 241868

Sure, "addresses" and "commands" can be freely combined:

sed '2s/harry/potter/g'

Upvotes: 1

Related Questions