sed [OPTIONS] [FILE]
-n, --quiet, --silent
suppress automatic printing of pattern space
--debug
annotate program execution
-e script, --expression=script
add the script to the commands to be executed
-f script-file, --file=script-file
add the contents of script-file to the commands to be executed
--follow-symlinks
follow symlinks when processing in place
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if SUFFIX supplied)
-l N, --line-length=N
specify the desired line-wrap length for the 'l' command
--posix
disable all GNU extensions.
-E, -r, --regexp-extended
use extended regular expressions in the script (for
portability use POSIX -E).
-s, --separate
consider files as separate rather than as a single, continuous
long stream.
--sandbox
operate in sandbox mode (disable e/r/w commands).
-u, --unbuffered
load minimal amounts of data from the input files and flush
the output buffers more often
-z, --null-data
separate lines by NUL characters
--help
display this help and exit
--version
output version information and exit
Print all with “abc”
/abc/p
Print all without “abc”
/abc/!p
Delete all with “abc”
/abc/d
Delete all without “abc”
/abc/!d
/start/,/end/!d
/abc/{s/def/ghi)}
Append ‘Hallo’ after each line
aHallo
Append ‘Hallo’ after line #5
5 aHallo
Append ‘Hallo’ to end of file
$ aHallo
sed -i '1s;^;new line 1\nanother new line 2\n;' <file>
To edit file use the -i option this safely changes the file contents without any output redirection needed.
sed -i 's/abc/ABC/' myfile.txt
sed -i '/deleteme/d' *
Often grep and sed are used together. In all those cases grep can be dropped. For example
grep "pattern" file | sed "s/abc/def/"
can be written as
sed -n "/pattern/p; s/abc/def/"
Always use single quotes!
sed 's/^.*\(pattern\).*/\1/'
If you want to do extraction and need a pattern based on single quotes use \x27 instead of trying to insert a single quote. For example:
sed 's/.*var=\x27\([^\x27]*\)\x27.*/\1/'
to extract “some string” from “var='some string’". Or if you don’t know about the quoting, but know there are quotes
sed 's/.*var=.\([^"\x27]*\)..*/\1/'
sed '/conditional pattern/{s/pattern/replacement/g}'
sed -i '1s/^/# DO NOT TOUCH THIS FILE!\n\n/' *
The only way to remove new line is this:
sed ':a;N;$!ba;s/\n//g' file
sed '/first line/,/last line/!d' file