遇到一些问题,需要处理log文件,但是只需要取log文件里命中某个关键字的一行,以及其前一行和后4行。
发现这种情况下grep很好用:
#!/bin/bash file_name="dphr_res" [ $# == 1 ] && file_name=$1 echo "file_name is $file_name" test ! -e $file_name && echo "$file_name is not exsit" && exit -1 cat $file_name | grep -x -A4 -B1 --color=auto 'id: 1 '
由于待查找的关键字为"id: 1 ",带有2个空格,直接使用" "无法正确识别,使用' '可以查找带空格的关键字。
-x是按照整行严格匹配,-A为显示命中行后的x行,-B为显示名中行前的x行。