5

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.

AndreasKralj
  • 463
  • 4
  • 23

1 Answers1

5

@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
AndreasKralj
  • 463
  • 4
  • 23