Using sed to edit files in place…

The other day I ran across a scenario where I needed to edit a file via a web app. Seems simply, but the file permissions were tricky and I didn’t have the rights to delete the file then re-create again since the top level directory permission wont allow it. So the easiest solution is to use sed to edit the file in place. The sed command can be called from inside the web app as long as the file we are editing has the proper permissions.

What is sed?

sed is a Stream Editor, hence the name. Normally you would use it to edit data coming in via STDIN or a STDOUT redirect. But the “-i” flag allows you to edit a flat file in place. Lets look at a few examples, take the following file contents:

Date: Dec 15th, 2019

TODO LIST
Clean house
Take out garbage
Buy groceries
Feed the fish
Watch TV

Lets say I want to edit this file in place and delete the line “Buy groceries”. There are few ways to do this, I can delete it via the line # or via regular expressions. The line # is 6, so the command would be:

# sed -i ” ‘6d’ /some/path/to/filename.txt

Note the empty set of single quotes after the -i, this is required for newer versions of sed, -i tells it to edit the file in place without creating a backup extension file. The ‘6d’ simply tells it to delete the 6th line of the file. Here is how you do it via regular expressions:

# sed -i ” ‘/^Buy.*/d’ /some/path/to/filename.txt

Again the d tells it to delete, the regular expression is inside the forward slashes, in this case the REGEX is find something that matches beginning of line word Buy, followed by anything.