Sed – match something, then change something else

Here’s a useful feature of sed, the linux stream editor, that I didn’t know about before.

My problem was that within a file, I wanted to only operate on lines that contained a certain expression – but leaving that expression intact and instead changing another expression on that line.

The standard sed command for replacing one expression with another is

sed 's/foo/bar/'

which replaces ‘foo’ with ‘bar’ on every line where ‘foo’ is found. But what if you only want to carry out that replacement on lines that contain the word ‘gnu’? The solution is this…

sed '/gnu/s/foo/bar/'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s