批处理之家's Archiver

netdzb 发表于 2019-8-6 09:42

sed和grep如何打印出匹配条件的上一行

我知道sed命令和grep配合可以完成此功能。
但不知道代码如何写?

Batcher 发表于 2019-8-6 11:01

不知道你要的是哪种效果

[centos7]# cat 1.txt
bbs
bathome
net

[centos7]# [color=Blue]grep -B 1 "bathome" 1.txt[/color]
bbs
bathome

[centos7]# [color=Blue]awk '/bathome/{print a}{a=$0}' 1.txt[/color]
bbs

[centos7]# [color=Blue]sed '$!N;/bathome/{P;d};D' 1.txt[/color]
bbs

netdzb 发表于 2019-8-6 11:24

[b]回复 [url=http://www.bathome.net/redirect.php?goto=findpost&pid=222532&ptid=53545]2#[/url] [i]Batcher[/i] [/b]

比如用sed匹配net,我想打印它的上一行bathhome

Batcher 发表于 2019-8-6 13:18

[b]回复 [url=http://bbs.bathome.net/redirect.php?goto=findpost&pid=222533&ptid=53545]3#[/url] [i]netdzb[/i] [/b]


    把2楼sed命令里面的bathome改成net

netdzb 发表于 2019-8-6 16:15

[b]回复 [url=http://www.bathome.net/redirect.php?goto=findpost&pid=222538&ptid=53545]4#[/url] [i]Batcher[/i] [/b]

我是想找一个sed和grep利用管道配合的例子。用这种方法可以做出来吗?

Batcher 发表于 2019-8-6 17:15

[b]回复 [url=http://bbs.bathome.net/redirect.php?goto=findpost&pid=222542&ptid=53545]5#[/url] [i]netdzb[/i] [/b]


    既然sed可以实现,为啥还要管道和grep呢。至于如何实现,请等等看其他人是否有好的方案吧 :)

页: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.