According to http://linux.about.com/od/commands/l/blcmdl1_sed.htm
suppress automatic printing of pattern space
I've tested with or without -n
, sed will produce same result
I dont understand what space does it means.
Sed has two places to store text: pattern space and hold space. Pattern space is where each line is put to be processed by sed commands; hold space is an auxiliary place to put some text you may want to use later. You probably will use only pattern space.
Before sed goes to process a line, it is put in the pattern space. Then, sed applies all commands (such as s///
) to de pattern space and, by default, prints the resulted text from the pattern space. Let us suppose we have a file myfile
with a line like:
The quick brown fox jumps over the lazy dog.
We run the following command:
sed 's/fox/coati/;s/dog/dingo/' myfile
Sed will apply s/fox/coati/
and then s/dog/dingo/
for each line of the file - in this case, the only one we showed above. When it occurs, it will put the line in the pattern space, which will have the following content:
The quick brown fox jumps over the lazy dog.
Then, sed will run the first command. After sed runs the command s/fox/coati/
, the content of the pattern space will be:
The quick brown coati jumps over the lazy dog.
Then sed will apply the second command, which is s/dog/dingo/
. After that, the content of the pattern space will be:
The quick brown coati jumps over the lazy dingo.
Note that this only happens in memory - nothing is printed by now.
After all commands have been applied to the current line, by default, sed will then get the content of the pattern space and print it to the standard output. However, when you give -n
as an option to sed, you are asking sed to do not execute this last step except if it is explicit required. So, if you run
sed -n 's/fox/coati/;s/dog/dingo/' myfile
nothing will be printed.
But how could you explicitly request sed to print the pattern space? Well, you can use the p
command. When sed finds this command, it will print the content of the pattern space immediately. For example, in the command below we request sed to print the content of the pattern space just after the first command:
sed -n 's/fox/coat/;p;s/dog/dingo/' myfile
The result will be
$ sed -n 's/fox/coati/;p;s/dog/dingo/' myfile
The quick brown coati jumps over the lazy dog.
Note that only fox
is replaced. It happens because the second command were not executed before the pattern space being printed. If we want to print the pattern space after both commands, we just put p
after the second one:
sed -n 's/fox/coati/;s/dog/dingo/;p' myfile
Another option, if you are using the s///
command, is to pass the p
flag to s///
:
sed -n 's/fox/coati/;s/dog/dingo/p' myfile
In this case, the line will only be printed if the flagged replacement was executed. It may be very useful!