Skip to content
Advertisement

Use awk to match a word, then find the first occurrence of another word

I am trying to find a way to re-search for another matching word after I already had a match.

I am specifically trying to get the brightness value of one of my monitors. For example a part of the output of my xrandr --verbose is the following:

JavaScript

I want to look for the word connected and then get the first occurrence of the word Brightness.

What I have tried which works is the following:

JavaScript

Which gives me the following output, because I have two monitors:

JavaScript

But assuming I only want the first occurrence for a result I have tried this:

JavaScript

Which works as intended giving me the value of brightness for this specific monitor.

But I am not sure whether the Brightness value is always on 5 lines later. So I was looking for a more robust solution.

Advertisement

Answer

awk solution:

JavaScript

  • /LVDS-1/{f=1} – on encountering line with needed LVDS-1 set flag f=1

  • /Brightness:/ && f – when encountering the closest line with Brightness: and active flag f (for LVDS-1) – print the value and exit the script execution immediately (to avoid redundant iterations)

Advertisement