Ubuntu – How to pass string variable as parameter to awk

awkcommand linescripts

I have following command:

usb_soundcard_sink=$(pactl list short sinks | grep "alsa_output" | awk '{ print $2 }' | tail -n1)

output of this command is:

alsa_output.pci-0000_00_1b.0.analog-stereo

And this is another command that find index number:

var=$(pactl list short sinks | awk '$2=="alsa_output.pci-0000_00_1b.0.analog-stereo" {print $1}')

output:

0

But I want pass the "usb_soundcard_sink" variable instead of hard coded value i.e. "alsa_output.pci-0000_00_1b.0.analog-stereo" in above command. b'coz value of "usb_soundcard_sink" variable may change dynamically.

Also I tried the following:

var=$(pactl list short sinks | awk '$2=="$usb_soundcard_sink" {print $1}')

But it is not working

so how can I pass value of "usb_soundcard_sink" variable to the above command

Best Answer

To use bash variables inside your awk, you have to use the -v syntax like this:

pactl list short sinks | awk -v myvar="$usb_soundcard_sink" '$2==myvar {print $1}'
#                               ^^^^^                            ^^^^^
#                                 |________________________________|

Example

$ a=3
$ awk -v myvar="$a" 'BEGIN{print myvar}'
3
Related Question