Use sed to modify files in place

sed command FAQ: How can I use the Unix/Linux sed command to edit (modify) files in place?

The short answer is that you just need to use the -i or --in-place sed arguments, as shown in the sed man page:

-i[SUFFIX], --in-place[=SUFFIX]

edit files in place (makes backup if extension supplied)

Then, if you have a file named 'hello.txt' with contents like this:

jello, world
this is a test

you can then run a sed command like this to modify that file:

sed -i -e 's/hello/jello/' hello.txt

That simple sed command changes the first 'hello' on each line to 'jello'. Not a great example, but simple enough.

Notice that this sed command with the -i option overwrites your original hello.txt file, so of course you want to be very careful with this command, and make backups of your original files, and move them to other directories before issuing this command.

Make a backup of your file while sed edits the original file

As you can see from the sed man page, you can also provide a file suffix, and sed will make a backup of your original file, using the suffix you provide. So a command like this:

sed -i.bak -e 's/hello/jello/' hello

will create a backup file named hello.bak, which will contain your original file contents. Again, I strongly encourage you to make a backup of your files somewhere else, because when sed commands go wrong, they can wreak a lot of havoc.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.