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.

4
  • 3
    Are you looking for -C, e.g. grep -C 5? C is for context. You can also explicitly show lines -Before and -After your matches.
    – L3viathan
    Jul 30, 2018 at 18:58
  • Use the -A (after) and -B (before) command-line options in grep.
    – FBergo
    Jul 30, 2018 at 18:58
  • Or -A and -B for fine control.
    – Harald
    Jul 30, 2018 at 18:59
  • @L3viathan yeah you're totally right. Thanks a lot, I changed my post and credited you. Jul 30, 2018 at 19:05

1 Answer 1

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.