Overview (sed, a stream editor)
Next: Command-Line Options, Up: Invoking sed [Contents][Index]
2.1 Overview
Normally sed is invoked like this:
sed SCRIPT INPUTFILE...
For example, to replace all occurrences of ‘hello’ to ‘world’ in the file input.txt:
sed 's/hello/world/' input.txt > output.txt
If you do not specify INPUTFILE, or if INPUTFILE is -, sed filters the contents of the standard input. The following commands are equivalent:
sed 's/hello/world/' input.txt > output.txt sed 's/hello/world/' < input.txt > output.txt cat input.txt | sed 's/hello/world/' - > output.txt
sed writes output to standard output. Use -i to edit files in-place instead of printing to standard output. See also the W and s///w commands for writing output to other files. The following command modifies file.txt and does not produce any output:
sed -i 's/hello/world/' file.txt
By default sed prints all processed input (except input that has been modified/deleted by commands such as d). Use -n to suppress output, and the p command to print specific lines. The following command prints only line 45 of the input file:
sed -n '45p' file.txt
sed treats multiple input files as one long stream. The following example prints the first line of the first file (one.txt) and the last line of the last file (three.txt). Use -s to reverse this behavior.
sed -n '1p ; $p' one.txt two.txt three.txt
Without -e or -f options, sed uses the first non-option parameter as the script, and the following non-option parameters as input files. If -e or -f options are used to specify a script, all non-option parameters are taken as input files. Options -e and -f can be combined, and can appear multiple times (in which case the final effective script will be concatenation of all the individual scripts).
The following examples are equivalent:
sed 's/hello/world/' input.txt > output.txt sed -e 's/hello/world/' input.txt > output.txt sed --expression='s/hello/world/' input.txt > output.txt echo 's/hello/world/' > myscript.sed sed -f myscript.sed input.txt > output.txt sed --file=myscript.sed input.txt > output.txt
Next: Command-Line Options, Up: Invoking sed [Contents][Index]