The table below will sum it up nicely, I think. Examples will follow the table.
Command
What it does
#
Comment
p
Print on the standard output.
d
Delete the line
q
The sed tool will exit
s/regexp/change/k
Replace. It will replace the regular expression found (regexp) with the change text. Inside the change text, we can use further expressions.
n
Remember that at the regular expressions we could refer back to a found expression surrounded by the n-th (). With this you can use the same approach, but inside the change text to refer back to found expressions inside the regexp.
&
The whole regular expression
In place of the k you can use the following:
g
Global replace. For all the matches, make the replacement.
n
n is an integer. Replace the n-th occurrence.
I
Do a non-case-sensitive pattern matching.
Address{
Command1;
Command2;
Command3;
...
}
We can group the sed commands in order to execute at a single step more. For example, a replace in the pattern space and print would look like this:
sed -n '/^mas/{s/a/b/;p}'
y/set_1/set_2
Replace the characters. In the two sets, the same number of characters must be present.
a
text
Append to the pattern space.
With the we refer to a new line.
After you use these commands, the step will stop to execute any further commands on the pattern space.
i
text
Insert text prior to the pattern space.
c
text
Replace the pattern space with the text.
=
Print the address of the current line.
r file
Read a file in. Only a single address may come before this.
If it fails to read the file, it will continue its work with no error messages. The file will be printed after the current line.
w file
Print the content of the pattern space to the file.
If the file it does not exist, it will create it.
n
Take the next line. Do not restart the mechanism of the sed.
Delete all the lines containing a single "a" character:
cat alfa.txt | sed -r '/^a$/d'
Replace the name Avril with Hilary in a file:
cat alfa.txt | sed -r 's/Avril/Hilary/g'
Reverse the name Avril Lavigne to Lavigne, Avril:
cat alfa.txt | sed -r 's/(Avril)(Lavigne)/2,1/g'
Search for the first Avril name in the file, print the row number and exit:
cat alfa.txt | sed -r '/Avril/{=;q}
Moreover, a classic example is to leave in a file with three columns (separated by a space) only the second one: