rrr*_*lsz 7 bash shell awk grep
使用grep,您可以打印与您的搜索查询匹配的行。添加一个-C选项将打印两行周围的上下文,如下所示:
> grep -C 2 'lorem'
some context
some other context
**lorem ipsum**
another line
yet another line
Run Code Online (Sandbox Code Playgroud)
同样,您可以使用grep -B 2或grep -A 2分别打印前两行或后两行的匹配行,例如:
> grep -A 2 'lorem'
**lorem ipsum**
another line
yet another line
Run Code Online (Sandbox Code Playgroud)
是否可以跳过匹配的行并只打印上下文?具体来说,我只想打印匹配项上方 2 行的行,如下所示:
> <some magic command>
some context
Run Code Online (Sandbox Code Playgroud)
grep如果您可以允许使用几个实例,您可以尝试像我在评论部分中提到的那样。
$ grep -v "lorem" < <(grep -A2 "lorem" file)
another line
yet another line
$ grep -A2 "lorem" file | grep -v "lorem"
another line
yet another line
Run Code Online (Sandbox Code Playgroud)
如果您对一剂感兴趣awk,有一个很酷的方法可以这样做:
$ awk -v count=2 '{a[++i]=$0;}/lorem/{for(j=NR-count;j<NR;j++)print a[j];}' file
another line
yet another line
Run Code Online (Sandbox Code Playgroud)
它的工作原理是将整个文件存储在自己的数组中,并且在搜索模式之后lorem,存储行号(NR)的 awk 特殊变量指向找到模式的确切行。awk如果我们按照变量的指示在它之前循环 2 行-v count,我们就可以打印所需的行。
如果您也对打印图案感兴趣,只需将 for 循环中的条件更改为 as 而j<=NR不是j<NR。就是这样!
| 归档时间: |
|
| 查看次数: |
1431 次 |
| 最近记录: |