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)
As an example, 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
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.