sed -n '/s1/,/s2/p' file 注意点

$ sed -n "/00:00:01/p" nls.log 
     1\t223.104.7.59 - - [05/Dec/2018:00:00:01 +0000] "
     4\t139.180.131.123 - - [05/Dec/2018:00:00:01 +0000] "
     9\t139.180.131.123 - - [05/Dec/2018:00:00:01 +0000] "
    10\t117.136.39.87 - - [05/Dec/2018:00:00:01 +0000] "
$ sed -n "/00:00:02/p" nls.log 
     2\t123.125.71.60 - - [05/Dec/2018:00:00:02 +0000] "
     3\t141.8.142.131 - - [05/Dec/2018:00:00:02 +0000] "
$ sed -n "/00:00:01/,/00:00:02/p" nls.log 
     1\t223.104.7.59 - - [05/Dec/2018:00:00:01 +0000] "
     2\t123.125.71.60 - - [05/Dec/2018:00:00:02 +0000] "
     4\t139.180.131.123 - - [05/Dec/2018:00:00:01 +0000] "
     5\t40.77.167.60 - - [05/Dec/2018:00:00:03 +0000] "
     6\t204.141.42.226 - - [05/Dec/2018:00:00:04 +0000] "
     7\t40.77.167.60 - - [05/Dec/2018:00:00:04 +0000] "
     8\t127.0.0.1 - - [05/Dec/2018:00:00:04 +0000] "
     9\t139.180.131.123 - - [05/Dec/2018:00:00:01 +0000] "
    10\t117.136.39.87 - - [05/Dec/2018:00:00:01 +0000] "
    11\t121.15.166.147 - - [05/Dec/2018:00:00:07 +0000] "
    12\t219.142.131.122 - - [05/Dec/2018:00:00:07 +0000] "
    13\t61.132.54.2 - - [05/Dec/2018:00:00:07 +0000] "
    14\t103.75.152.102 - - [05/Dec/2018:00:00:07 +0000] "
    15\t222.66.96.129 - - [05/Dec/2018:00:00:07 +0000] "
    16\t180.168.166.28 - - [05/Dec/2018:00:00:07 +0000] "
    17\t114.94.126.62 - - [05/Dec/2018:00:00:07 +0000] "
    18\t61.135.169.90 - - [05/Dec/2018:00:00:07 +0000] "
    19\t120.36.255.107 - - [05/Dec/2018:00:00:07 +0000] "
    20\t14.21.33.152 - - [05/Dec/2018:00:00:07 +0000] "

sed -n ‘/s1/,/s2/p’ file
sed 会逐行读取文件到模式空间,也就是一个临时缓存,然后执行sed后面的命令,然后输出打印模式空间的内容,然后清空模式空间;
接着读文件的下一行,重复前面的步骤,直到文件内容处理完为止。
如果没有-n,匹配到的内容比如s1会被再次打印,s1总共就会被打印2次(假设s1只匹配到1行)。
如果有-n 那么会抑制默认打印,只打印匹配到的内容。
‘/s1/,/s2/p’ 表示打印s1和s2所在行及之间的内容。
所以,可以推断出s1和s2直接的内容是被存到模式空间,并且会被打印的。
那么,当s1匹配成功,s2匹配失败时,打印的是s1及s1到最后1行
案例中,$ sed -n “/00:00:01/,/00:00:02/p” nls.log 的/00:00:01/的所在4/9/10行都必/00:00:02/所在2/3行大,
而/00:00:01/所在行是1,所以会打印所有。

关闭