web123456

Deeply understand the usage of -n and -p options in sed

First, let me introduce the meaning of these two options of the sed command:

  • -n option: only matched rows are displayed (otherwise all will be output) (That is, turn off the default output
  • -p option: Print
[root@centos6 ~]# vim
 [root@centos6 ~]# cat
 asdf;1324;fdsag
 1234567890
 qwer
 asdasdsadasdasdas
 [root@centos6 ~]# sed 's/1324/aaaa/' > First of all, sed has a default output, that is, output all file contents and add the replacement in the command line, so the output result is as follows
 [root@centos6 ~]# cat
 asdf;aaaa;fdsag
 1234567890
 qwer
 asdasdsadasdasdas
 [root@centos6 ~]# sed 's/1324/aaaa/p' > This line means: first, sed default outputs all the contents of the file, and then p prints the matching contents again, which means that the matching contents will be output
 [root@centos6 ~]# cat
 asdf;aaaa;fdsag
 asdf;aaaa;fdsag
 1234567890
 qwer
 asdasdsadasdasdas
 [root@centos6 ~]# sed -n 's/1324/aaaa/p' > This line is sed -n blocking the default output and then replacing s, and p prints the matching content, so only one line is displayed, that is, the matching line
 [root@centos6 ~]# cat
 asdf;aaaa;fdsag
 [root@centos6 ~]# sed -n 's/1324/aaaa/' > This line is the sed -n option blocks the default output, s is replaced, but without p, the matching content will not be output
 [root@centos6 ~]# cat
 [root@centos6 ~]#

No matter what other usages are used during the use of sed, it will involve the display problem of the -n option and the printing problem of the -p option.