How to pass string variable as parameter to awk

67,961

Solution 1

To pass a inside into your awk code, you have to use the -v syntax like this:

$ awk -v myvar="3" 'BEGIN{print myvar}'
#     \__________/              \___/          
3

In your specific case, just use:

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

Solution 2

I found that this works too

line=myfile.dat
f=8
s=11
echo $line | awk '{print $'$f',$'$s'}'

Here I have a file called myfile.dat piped into awk which spits out column 8 and 11.

Share:
67,961

Related videos on Youtube

Prakash V Holkar
Author by

Prakash V Holkar

Updated on September 18, 2022

Comments

  • Prakash V Holkar
    Prakash V Holkar over 1 year

    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

  • Admin
    Admin almost 2 years
    Sorry. Bad solution. Unreadable awk script :-(