Introduction
You use sed substitution to quickly find and replace text in files or outputs without opening them. It helps automate text changes in scripts.
sed 's/old-text/new-text/' filename # or for inline replacement in a script sed 's/old-text/new-text/g' <<< "$variable"
sed 's/cat/dog/' animals.txtsed 's/cat/dog/g' animals.txtsed 's/^Hello/Hi/' greetings.txtsed 's/dog/cat/' <<< "I have a dog and a dog."
#!/bin/bash # Create a sample file cat <<EOF > pets.txt I have a cat. My cat is cute. Cats are playful. EOF # Show original file echo "Original file contents:" cat pets.txt echo # Replace first 'cat' with 'dog' on each line sed 's/cat/dog/' pets.txt > pets_replaced.txt echo "After replacing first 'cat' with 'dog' on each line:" cat pets_replaced.txt echo # Replace all 'cat' (case sensitive) with 'dog' on each line sed 's/cat/dog/g' pets.txt > pets_replaced_all.txt echo "After replacing all 'cat' with 'dog' on each line:" cat pets_replaced_all.txt
sed command sed 's/cat/dog/' file.txt do?sed 's/cat/dog/' file.txt uses s/old/new/ which replaces only the first match per line.s/apple/orange/g which correctly replaces all 'apple' with 'orange'. sed 's/apple/orange/' file.txt replaces only first occurrence. sed 'replace apple with orange' file.txt is invalid syntax. sed 's/apple/orange//g' file.txt has extra slashes causing syntax error.apple apple apple?
sed 's/apple/orange/' file.txt
sed 's/foo/bar/' file.txt. But only the first 'foo' per line is replaced. What is the fix?/pattern/ s/old/new/flags syntax.Pass the test and this pattern moves unknown