rsk82
rsk82

Reputation: 29377

how to replace two things at once with sed?

Given is string: dog apple orange banana

I need to make it: monkey apple cow banana

That is without calling sed twice.

Upvotes: 43

Views: 48519

Answers (3)

Joe'
Joe'

Reputation: 476

This can also be done using capture groups, such as \(.*\), which are formed with parentheses, and back references, such as \1, \2, etc. that reference each capture group.

sed 's|dog\(.*\)orange\(.*\)|monkey\1cow\2|'

Upvotes: 1

Yasser Zamani
Yasser Zamani

Reputation: 2500

The following sed example should solve your problem. sed allows multiple -e switches, which allows you to replace more than one thing at a time.

sed -e 's/dog/monkey/g' -e 's/orange/cow/g'

Upvotes: 75

user123444555621
user123444555621

Reputation: 152956

Use ; to queue commands:

sed -e 's/dog/monkey/g;s/orange/cow/g'

Upvotes: 66

Related Questions