What does `-n` option in sed do?
Solution 1:
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 requestedsed '2,3p' test.txt
- prints each line (automatically), AND ALSO prints lines 2-3 a second timesed -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 firstp
command then the auto print), and line 3 three times (once for eachp
command, then again automatically).