[awk] conditional printing

Heya

I'm trying to get to know awk a bit better.
So i'm trying to get used to calls saving me a grep invocation just to get a specific part of a single line.

This said, i want to get the current screen resolution according to xrandr 's output.

Screen 0: minimum 8 x 8, current 1920 x 1080, maximum 32767 x 32767
eDP1 connected 1920x1080+0+0 (normal left inverted right x axis y axis) 344mm x 193mm
   1920x1080     60.06*+
   1400x1050     59.98  
   1280x1024     60.02  
   1280x960      60.00  
   1024x768      60.00  
   800x600       60.32    56.25  
   640x480       59.94  
HDMI1 disconnected (normal left inverted right x axis y axis)
VGA1 disconnected (normal left inverted right x axis y axis)
VIRTUAL1 disconnected (normal left inverted right x axis y axis)

So, the desired output would be: 1920x1080

So, in a first attempt, and according to another thread, i tried to apply and started with excluding those lines not containing the asterix.
They seemed to work quite fine, just that they didnt print any output.

$ xrandr|awk 'BEGIN { ! /*/ } { next }  { printf $1 }'
$ xrandr|awk 'BEGIN { ! /\*/ } { next }  { printf $1 }'
$ xrandr|awk 'BEGIN { ! /\*#/ } { next }  { printf $1 }'
$ xrandr|awk 'BEGIN { ! /*#/ } { next }  { printf $1 }'
$ xrandr|awk 'BEGIN { ! /#*/ } { next }  { printf $1 }'
$ xrandr|awk 'BEGIN { ! /#\*/ } { next }  { printf $1 }'
$ xrandr|awk '{ ! /#\*/ } { next }  { printf $1 }'

Then i thought, maybe its better to just check if the line contain the asterix and print just that one.

$ xrandr|awk '{ /*/ }  { printf $1 }'
ScreeneDP11920x10801400x10501280x10241280x9601024x768800x600640x480HDMI1VGA1VIRTUAL1
$ xrandr|awk '{ /\*/ }  { printf $1 }'
ScreeneDP11920x10801400x10501280x10241280x9601024x768800x600640x480HDMI1VGA1VIRTUAL1

What a change, but it prints the first column from every line.

Also, playing around with: (switching && with || and \* with * and >= with == / <= )

xrandr | awk '{ NR>=1 || /\*/ }  { printf $1 }'

Didnt change much, or i missed the working combination of those.

Any ideas?
Thank you in advance.

You're not too far off:

xrandr | awk '/\*/ {print $1}'
1280x1024

Don't surround the testing pattern with { } - it will become an action, then...
And, if using printf , don't forget the \n line terminator.

1 Like