search and replace sed code example

Example 1: linux replace string in all files

sed -i 's/old-text/new-text/g' input.txt

Example 2: sed replace in file

sed -i 's/foo/bar/g' hello.txt

Example 3: sed replace all occurances?

echo dog dog dos | sed -e 's:dog:log:g'

#You can also use the above answer with appropriate slashes like
echo "grepper is a nice grepper" | sed "s/grepper/blow/g"

Example 4: bash find and replace all files with specifc name with another file

find . -name "boom.txt" -exec cp ~/replace.txt {} \;

Example 5: sed replace with variable

For using match in sed replacement, just border it with '\(' and '\)':
echo Before123 | sed 's/Before\([0-9]*\)/\1After/g'
123After	# number is matched withtin '\( \)' and replaced in '\1'
Example with 2 match replacements
echo a_b | sed 's/\(^.*\)_\(.*$\)/first is \1 and \2 is after/g'

Tags:

C Example