参见英文答案 > grep a file, but show several surrounding lines? 11个
假设我正在使用lshw来获取系统内存,我希望它打印出来以便我只获得系统内存选项.你能指定在grep中字符串之前或之后打印多少行?下面输出lshw命令的片段以供参考:
description: Computer
width: 64 bits
*-core
description: motherboard
physical id: 0
*-memory
description: System memory
physical id: 0
size: 23GiB
*-cpu
product: Intel(R) Core(TM) i5-8350U cpu @ 1.70GHz
vendor: Intel Corp.
physical id: 1
bus info: cpu@0
capacity: 1896MHz
width: 64 bits
我可以使用lshw | grep尺寸| awk -F:'{print $2}’获取23 GiB部分,但是我想知道是否有办法用grep获取一个文本块来获取完整的内存部分.
解决方法:
@L3viathan帮助我搞清楚了. Grep有一个-A标志,允许您指定字符串后所需的行数.您还可以使用-B标志指定字符串之前所需的行数.
例子之后:
lshw | grep *-memory -A 3
输出:
*-memory
description: System memory
physical id: 0
size: 23GiB
例子之前:
lshw | grep size -B 3
输出:
*-memory
description: System memory
physical id: 0
size: 23GiB