Linux sed Command: Search and Replace Text Streams

sed is a stream editor that reads input line by line, applies editing rules, and outputs the results. It is suitable for repetitive text transformations, such as substitution, selecting specific lines, and deletion.

By default, it does not modify the original file and outputs the transformed result to standard output. The form of the substitution command is s/pattern_to_find/replacement_content/flags, and adding g replaces all matches in a line.

Basic syntax

sed [options] 'editing command' [file...]

Installed implementations and options may vary depending on the distribution. Check the description for your current system with man sed.

Compare original input, output, backups, and restoration

Run the complete block: it prepares every input in a new temporary directory inside a subshell and prints that directory at the end. It does not overwrite files in the current working directory. Inspect the results and remove only the lab data when it is no longer needed.

(
set -eu
labdir=$(mktemp -d)
cd "$labdir"
printf 'red car\nred red\n' > config.txt
sed 's/red/green/' config.txt > first.txt
sed 's/red/green/g' config.txt > all.txt
cat config.txt first.txt all.txt
cp config.txt editable.txt
sed -i.bak 's/red/green/g' editable.txt
diff -u editable.txt.bak editable.txt || test "$?" -eq 1
cmp config.txt editable.txt.bak
cp editable.txt.bak editable.txt
cmp config.txt editable.txt
printf 'Lab files: %s\n' "$labdir"
)

The original remains red car/red red. First-match substitution produces green car/green red; global substitution produces green car/green green. GNU sed -i.bak changes editable.txt and retains its earlier content in .bak. diff status 1 means differences were found, while successful cmp checks show the backup and restored content match the original. Check other implementations’ -i syntax and distinguish regular expressions such as .* from literal strings.

Main Options and Format

Options/Format Description
-n Turn off automatic printing by default.
-e script Specify multiple editing commands.
-E Use extended regular expressions.
-i[suffix] Edit files in place and optionally make a backup in the GNU implementation.

Precautions when using

`sed -i` actually modifies the file, so use a backup suffix for important files and review the results. The `-i` syntax differs between GNU and BSD. You also need to consider shell quoting and special characters in regular expressions.

Frequently Asked Questions

Does running just sed change the original file?

No. By default, it outputs the changed result. You need to use `-i` or save the result to a separate file to modify the file.

Official Documentation

You can check the exact behavior of options and differences between implementations in the official sed documentation.