%w(hashrockets spaceships bangbangs)

> non-optimized bits & pieces <

A Little Bit of Sed Kungfu

Just picked up a little bit of sed kungfu today while pairing with jeff.

In-place editing with “-i”

If you want to do in-place editing of a file, you can pass the -i option to sed. Let’s say we have the following file:

1
sed is cool

With:

1
$ sed -i /path/to/file -e 's/cool/awesome/'

We get:

1
sed is awesome

So how do i acheive this previously ?? This is embarrassing, it used to be like this:

1
2
$ cat /path/to/file | sed 's/cool/awesome' > /path/to/file.new
$ mv /path/to/file.new /path/to/file

Replacing only lines matching pattern

Let’s say you have the following file:

1
2
Vim is really cool,
& sed is cool as well.

We want to replace only the line with the occurrence of “sed”. We can acheive it using the script command /<pattern>/s/<original-text>/<replacement-text>, just like this:

1
sed -e '/sed/s/cool/awesome/' /path/to/file

This is what we get in stdout:

1
2
Vim is really cool,
& sed is awesome as well.

Happy Sed-ing :)

Comments