How to change the bash code to get still the screen resolution on ubuntu by xrandr, but without to use awk?
Solution 1:
First of all, there really is no reason to remove awk
. It is extremely fast, stable and made for this sort of thing. However, your command is needlessly complicated. You could simply do:
$ xrandr --current | awk '$2~/\*/{print $1}'
2560x1440
If you really need the x and y separately, do:
x=$(xrandr --current | awk '$2~/\*/{print $1}' | cut -d'x' -f1)
y=$(xrandr --current | awk '$2~/\*/{print $1}' | cut -d'x' -f2)
echo "$x"
echo "$y"
Or, more simply:
$ read x y < <(xrandr --current | awk '$2~/\*/{sub(/x/," ");print $1,$2}')
$ echo "x:$x y:$y"
x:2560 y:1440
And if you insist on not using awk, here are a few other options:
read x y < <(xrandr --current | sed -En '/\*/{s/^ *([0-9]+)x([0-9]+).*/\1 \2/p}')
echo "$x"
echo "$y"
or
read x y < <(xrandr --current | perl -lne 'print "$1 $2" if /^ *([0-9]+)x([0-9]+).*/')
echo "$x"
echo "$y"
or
read x y < <(xrandr --current | grep -oP '\d+x\d+' | tr x ' ')
echo "$x"
echo "$y"
Note that all of these assume only one screen is connected, as does your original approach.
Solution 2:
You can use a binary operator and read
:
[[ $(xrandr --current) \
=~ current\ ([0-9]+)\ x\ ([0-9]+) \
]] && read x y <<< "${BASH_REMATCH[@]:1:2}"
echo ${x}x${y}
The second variant creates a stride list with current modes.
#!/bin/bash
a=()
while read -r; do
[[ $REPLY \
=~ \ +([0-9]+)x([0-9]+)\ +[0-9.]+\* ]] && a+=(${BASH_REMATCH[@]:1:2})
done < <(xrandr --current)
# print the first resolution.
read x y <<< ${a[@]::2} && echo ${x}x${y}