2

Sample of output stored in a file:

Provides:        Red Hat Satellite
                 Red Hat Developer Toolset (for RHEL Server)
  SKU:                 TGV123
  Contract:            59104
  Pool ID:             abcdxyz12340987

From the above output, I want to look for "Red Hat Satellite" and look for the line containing "Pool ID:" so that I get the value of the pool ID i.e. abcdxyz12340987.

How can I obtain this using sed, awk or grep? "Pool ID" may appear several lines after "Red Hat Satellite" i.e. no set number of lines in between them.

Help much appreciated!

2
  • is there a set range of lines between them? There's better awk solutions out there, but here's something dirty: grep -A10 "Provides: Red Hat Satellite" file | grep "Pool ID:" | head -1 | awk '{print $2}' just change "A10" to the maximum amount of lines there is between the Provides line and the Pool ID line Commented Oct 18, 2019 at 9:06
  • @RobotJohnny, the lines vary, hence wanted something which will be independent of lines in between. The solutions below work. Commented Oct 18, 2019 at 12:03

2 Answers 2

2
sed -n '/Red Hat Satellite/,/Pool ID:/{ s/.*Pool ID:[[:blank:]]*\(.*\)/\1/p; }' file

This applies a substitution that picks out your string from after Pool ID:. It does this on any line between a line that contains the string Red Hat Satellite and the first line afterwards that contain Pool ID:. The command would print only the result of any successful substitution.

The following awk command would do the same, provided that the string at the end of the Pool ID: line does not contain any whitespace:

awk '/Red Hat Satellite/,/Pool ID:/ { if (/Pool ID:/) print $NF }' file

grep would not be the tool for this job as it is bad at handling context ("extract one line given some match on another line"). It would possibly work given some PCRE over nul-terminated lines using GNU grep, but it would be a hack.

4
  • If string Pool ID happened to be on the same line as the red hat line, then the awk solution wouldn't work. Range operators in sed n awk r different in where they test for the conditions. Commented Oct 18, 2019 at 8:57
  • @RakeshSharma This is true. It would not work for any provider whose name contains the string Pool ID:.
    – Kusalananda
    Commented Oct 18, 2019 at 9:53
  • @RakeshSharma they will always been on different lines. So no worries on that! Commented Oct 18, 2019 at 12:04
  • @Kusalananda, thanks for the solution! Commented Oct 18, 2019 at 12:06
1

With awk scripting:

$ awk '/Red Hat Satellite/{ f=1; next }f && /Pool ID:/{ print $NF; exit }' yourfile
abcdxyz12340987
1
  • This one works as well. Thanks! Commented Oct 18, 2019 at 12:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .