Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I grep a certain amount of lines before or after a string I want? [duplicate]

Tags:

regex

linux

bash

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.

like image 417
AndreasKralj Avatar asked Jul 30 '18 18:07

AndreasKralj


People also ask

How do you grep 5 lines before and after?

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.

How do you get 10 lines before and after grep?

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.

How do you grep two lines before and after?

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.

How do you grep the next 4 lines?

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.


1 Answers

@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
like image 118
AndreasKralj Avatar answered Sep 30 '22 03:09

AndreasKralj