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:
DP-1 connected 1920x1080+1920+0 (0x6e) normal (normal left inverted right x axis y axis) 598mm x 336mm Identifier: 0x46 Timestamp: 73906594 Subpixel: horizontal rgb Gamma: 1.0:1.0:1.0 Brightness: 1.0 Clones: CRTC: 1
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:
xrandr --verbose | awk '/ connected /{print $1}/Brightness:/{print $2}'
Which gives me the following output, because I have two monitors:
LVDS-1 1.0 DP-1 1.0
But assuming I only want the first occurrence for a result I have tried this:
xrandr --verbose | awk '/LVDS-1/{getline; getline; getline; getline; getline; print$0}'
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:
xrandr --verbose | awk '/LVDS-1/{f=1}/Brightness:/ && f{print $2; exit}'
/LVDS-1/{f=1}
– on encountering line with neededLVDS-1
set flagf=1
/Brightness:/ && f
– when encountering the closest line withBrightness:
and active flagf
(forLVDS-1
) – print the value andexit
the script execution immediately (to avoid redundant iterations)