27

This is the man page entry for -n:

-n

suppress automatic printing of pattern space

I notice that when not using -n for certain operations, each line is printed to stdout (and the requested lines are printed twice):

$ cat test.txt 
first
second
third
fourth
fifth

$ sed -n '2,3p' test.txt 
second
third

$ sed '2,3p' test.txt 
first
second
second
third
third
fourth
fifth

However, this law does not hold for other commands:

$ sed -n 's/t/T/' test.txt 

$ sed 's/t/T/' test.txt 
firsT
second
Third
fourTh
fifTh

So what does -n do, exactly?

dotancohen
  • 11,720

1 Answers1

31

Normally, sed processes each line (doing substitutions etc), then prints the result. If the processing involves the line being printed (e.g. sed's p command), then it gets printed twice (once during processing, then again by the automatic post-processing print). The -n option disables the automatic printing, which means the lines you don't specifically tell it to print do not get printed, and lines you do explicitly tell it to print (e.g. with p) get printed only once.

  • sed -n '2,3p' test.txt - prints only lines 2 through 3, as requested

  • sed '2,3p' test.txt - prints each line (automatically), AND ALSO prints lines 2-3 a second time

  • sed -n 's/t/T/' test.txt - replaces "t" with "T" on each line, but doesn't print the result due to -n

  • sed 's/t/T/' test.txt - replaces "t" with "T" on each line, and automatically prints the result

And let me add some more examples:

  • sed -n 's/t/T/p' test.txt - replaces "t" with "T" on each line, prints ONLY lines where the substitution took place (i.e. not "second")

  • sed 's/t/T/p' test.txt - replaces "t" with "T" on each line, prints lines where the substitution took place, then automatically prints each line (result: "second" is printed once, all the others twice)

  • sed '2,3p; 3p' test.txt - prints lines 1, 4, and 5 once (the auto print); line 2 twice (the first p command then the auto print), and line 3 three times (once for each p command, then again automatically).