linux 打印匹配内容前、后行

linux 打印匹配内容前、后行

样例:

cat test.txt
aaaa
bbbb
cccc
dddd
eeee
ffff
gggg
hhhh
iiii

使用sed

使用sed过滤指定行!(以过滤eeee为例)

#匹配eeee所在行,并打印eeee后3行
sed -n '/eeee/,+3p' test.txt
https://qnimg.ffing.cn/wp-content/uploads/2022/01/image-26.png?imageView2/0/q/75|watermark/1/image/aHR0cHM6Ly9xbmltZy5mZmluZy5jbi9mbl9sb2dvLnBuZw==/dissolve/55/gravity/SouthEast/dx/0/dy/0

打印匹配行的上一行

#x交换空间,p打印,h当前模式空间中内容覆盖至缓存区
#sed命令参数太过复杂,暂时记录这这里
sed -n '/eeee/{x;p};h' test.txt
https://qnimg.ffing.cn/wp-content/uploads/2022/01/image-27.png?imageView2/0/q/75|watermark/1/image/aHR0cHM6Ly9xbmltZy5mZmluZy5jbi9mbl9sb2dvLnBuZw==/dissolve/55/gravity/SouthEast/dx/0/dy/0

使用grep

使用grep先确定匹配行号,再对行号前后增加!(以过滤eeee为例)

#获取eeee行号
cat test.txt |grep -nE "^eeee$"|awk -F":" '{print $1}'
https://qnimg.ffing.cn/wp-content/uploads/2022/01/image-28.png?imageView2/0/q/75|watermark/1/image/aHR0cHM6Ly9xbmltZy5mZmluZy5jbi9mbl9sb2dvLnBuZw==/dissolve/55/gravity/SouthEast/dx/0/dy/0
#获取eeee所在行号
NUM=`cat test.txt |grep -nE "^eeee$"|awk -F":" '{print $1}'`
#eeee所在行号的上一行
NUM_1=`echo "$NUM-1"|bc`
#eeee所在行号的下一行
NUM1=`echo "$NUM+1"|bc`

 sed -n "$NUM_1"p test.txt
 sed -n "$NUM"p test.txt
 sed -n "$NUM1"p test.txt

执行结果如下:

https://qnimg.ffing.cn/wp-content/uploads/2022/01/image-29.png?imageView2/0/q/75|watermark/1/image/aHR0cHM6Ly9xbmltZy5mZmluZy5jbi9mbl9sb2dvLnBuZw==/dissolve/55/gravity/SouthEast/dx/0/dy/0

good good study, day day up!

发表评论

textsms
account_circle
email

linux 打印匹配内容前、后行
样例: cat test.txt aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii 使用sed 使用sed过滤指定行!(以过滤eeee为例) #匹配eeee所在行,并打印eeee后3行 sed -n '/eeee/,+3p…
扫描二维码继续阅读
2022-01-22