0
#!/user/bin/bash
a=$1
echo $1
awk '$1=="$a"{print $2}' Test.txt

I am trying to assign a value to $a dynamically and check that value in text file using awk. if $1 is equal to $a then it should display $2 in the text file.


A HIGH

B LOW

C MEDIUM

D HELLO

E Hai


I tried passing $a hardcoded in awk and it worked and provided me the expected output but I am not able to pass a variable in that place


#!/user/bin/bash
a=$1
echo $1
awk '/A/ {print $2}' Test.txt

I am looking for a way to pass a value to $a dynamically while running the shell script

usersas
  • 27
  • 5
  • I came up with this script to get my output. `#!/bin/bash` `a=$1` var=`grep $1 Test.txt | awk '{print $2}'` – usersas Jun 07 '18 at 09:33

1 Answers1

1

You can pass variables to awk like this:

awk -v var=$1 '{print var}'

Pri.txt:

A High
B Low
C Medium

display.sh:

#!/bin/bash

awk -v a=$1 '$1 == a {print $2}' Pri.txt

Output:

$ ./display.sh A
High
Alex Stiff
  • 844
  • 5
  • 12
  • I tried the following but still It is not working `awk -v ses=$1 '{if(ses==$1) print $2 }' Test.txt` – usersas Jun 06 '18 at 10:05
  • What's inside the variable $1? What about the Test.txt file? – Alex Stiff Jun 06 '18 at 12:15
  • $1 value changes dynamically. It gets it's input manually while I run the script and Test.txt has two coulmns. I have to match the $1 value that i get manually in the Test.txt and display the respective column – usersas Jun 07 '18 at 09:32
  • I mean specifically in your example where you said "I tried the following". What was the specific value of $1 here? What about Test.txt? – Alex Stiff Jun 07 '18 at 14:20
  • I passed a string as an input for $1 – usersas Jun 07 '18 at 15:14
  • What string?? Help me to help you, please. What was the string? What are the contents of Test.txt? – Alex Stiff Jun 08 '18 at 10:21
  • So I passed $1 = A. And in my text file, I will have A High,B Low, C Medium. If I pass A, it must display High. Below is the script I eneded up doing for the above mentioned problem. #!/bin/bash a=$1 var=`grep $1 Pri.txt | awk '{print $2}'` echo $var – usersas Jun 11 '18 at 06:01
  • I've edited my answer - let me know if this clears things up. – Alex Stiff Jun 11 '18 at 08:31