Andy
Andy

Reputation: 613

How to use sed against specific line in a file

There are two instances of a word music in a file.

Hello music
Goodbye music

If I were to use sed to replace an instance of music only where grep Hello is applied, what would I need to add to a sed comand?

Currently sed -i -e "s/$olmusic/$newmusic/g" file.txt replaces every instance of $oldmusic in a file but I need it to replace only the one where condition of grep is met.

Upvotes: 0

Views: 45

Answers (2)

Cyrus
Cyrus

Reputation: 88563

I suggest:

sed -i "/Hello/{s/$olmusic/$newmusic/}" file.txt

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 157947

sed offers to use a regex as an address:

sed -i -e "/Hello/s/$olmusic/$newmusic/" file.txt

Upvotes: 0

Related Questions