Extract multiple lines if match

awktext processing

I have a command that outputs information about all DIMM slots in blocks like the following:

ID    SIZE TYPE
44    105  SMB_TYPE_MEMDEVICE (type 17) (memory device)

  Manufacturer: NO DIMM
  Serial Number: NO DIMM
  Asset Tag: NO DIMM
  Location Tag: P1-DIMMD1
  Part Number: NO DIMM

  Physical Memory Array: 43
  Memory Error Data: Not Supported
  Total Width: 0 bits
  Data Width: 0 bits
  Size: Not Populated
  Form Factor: 9 (DIMM)
  Set: None
  Rank: Unknown
  Memory Type: 2 (unknown)
  Flags: 0x4
        SMB_MDF_UNKNOWN (unknown)
  Speed: Unknown
  Configured Speed: Unknown
  Device Locator: P1-DIMMD1
  Bank Locator: P0_Node1_Channel0_Dimm0
  Minimum Voltage: 1.20V
  Maximum Voltage: 1.20V
  Configured Voltage: 1.20V

The blocks start with the ID SIZE TYPE header and end with the configured voltage information. The command outputs one of these blocks of data for each DIMM separated by a single blank line each.


I would like to be able to get the block of information for a specific DIMM slot based on the Location Tag field, but am unsure how to go about it. I am pretty sure this can be done with awk but only know how to print the match awk '/P1-DIMMD1/' or the line prior to match awk '/P1-DIMMD1/ {print a}{a=$0}'

Does anyone know how I could extract this whole block of data if the Location Tag matches my search (P1-DIMMD1)?

Best Answer

The following will match the tag given in the tag variable:

awk -v tag=P1-DIMMD1 '/ID    SIZE TYPE/ { block = $0; output = 0; next } { block = block "\n" $0 } /Location Tag/ { output = ($0 ~ tag) } /Configured Voltage/ && output { print block }'

The AWK script is

/ID    SIZE TYPE/ {
  block = $0
  output = 0
  next
}

{ block = block "\n" $0 }

/Location Tag/ { output = ($0 ~ tag) }

/Configured Voltage/ && output { print block }

We accumulate a block in the block variable, and output it when we reach the end of the block if we saw the right tag in the process.

Related Question