I am trying to find out if it is possible to edit a file in a single sed command without manually streaming the edited content into a new file and
Like Moneypenny said in Skyfall: "Sometimes the old ways are best." Kincade said something similar later on.
$ printf ',s/false/true/g\nw\n' | ed {YourFileHere}
Happy editing in place. Added '\nw\n' to write the file. Apologies for delay answering request.
Versions of sed
that support the -i
option for editing a file in place write to a temporary file and then rename the file.
Alternatively, you can just use ed
. For example, to change all occurrences of foo
to bar
in the file file.txt
, you can do:
echo ',s/foo/bar/g; w' | tr \; '\012' | ed -s file.txt
Syntax is similar to sed
, but certainly not exactly the same.
Even if you don't have a -i
supporting sed
, you can easily write a script to do the work for you. Instead of sed -i 's/foo/bar/g' file
, you could do inline file sed 's/foo/bar/g'
. Such a script is trivial to write. For example:
#!/bin/sh -e
IN=$1
shift
trap 'rm -f $tmp' 0
tmp=$( mktemp )
<$IN "$@" >$tmp && cat $tmp > $IN # preserve hard links
should be adequate for most uses.
The -i option streams the edited content into a new file and then renames it behind the scenes, anyway.
Example:
sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
and
sed -i '' 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename
on macOS.
The following works fine on my mac
sed -i.bak 's/foo/bar/g' sample
We are replacing foo with bar in sample file. Backup of original file will be saved in sample.bak
For editing inline without backup, use the following command
sed -i'' 's/foo/bar/g' sample
On a system where sed
does not have the ability to edit files in place, I think the better solution would be to use perl
:
perl -pi -e 's/foo/bar/g' file.txt
Although this does create a temporary file, it replaces the original because an empty in place suffix/extension has been supplied.
Very good examples. I had the challenge to edit in place many files and the -i option seems to be the only reasonable solution using it within the find command. Here the script to add "version:" in front of the first line of each file:
find . -name pkg.json -print -exec sed -i '.bak' '1 s/^/version /' {} \;