Let's say I'm using lshw to get my system memory, and I want it printed out so that I only get the system memory option. Can you specify how many lines you want to print before or after a string in grep? A snippet of the lshw command is output below for reference:
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
I could use lshw | grep size | awk -F: '{print $2}'
to get the 23 GiB portion, but I want to see if there's a way to get a block of text with grep to get the full memory section.
You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.
You can use the -B and -A to print lines before and after the match. Will print the 10 lines before the match, including the matching line itself.
For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.
To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.
@L3viathan helped me figure it out. Grep has an -A flag that allows you to specify how many lines you want after the string. You can also use the -B flag to specify how many lines you want before the string.
After Example:
lshw | grep *-memory -A 3
Output:
*-memory
description: System memory
physical id: 0
size: 23GiB
Before Example:
lshw | grep size -B 3
Output:
*-memory
description: System memory
physical id: 0
size: 23GiB
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With