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
IN=$1
shift
trap 'rm -f "$tmp"' 0
tmp=$( mktemp )
<"$IN" "$@" >"$tmp" && cat "$tmp" > "$IN" # preserve hard links
should be adequate for most uses.
-i
is an option in gnu sed, but is not in standard sed. However, it streams the content to a new file and then renames the file so it is not what you want. – Genyed
rather thansed
, or you stream via a memory buffer usingsed "$f" | sponge "$f"
, or you could install GNU sed. Which of those best addresses your particular situation is beyond our knowledge (for one thing, it probably depends on the size of file you are processing). – Keldah