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

1
  • I came up with this script to get my output. #!/bin/bash a=$1 var=grep $1 Test.txt | awk '{print $2}' Commented Jun 7, 2018 at 9:33

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

8 Comments

I tried the following but still It is not working awk -v ses=$1 '{if(ses==$1) print $2 }' Test.txt
What's inside the variable $1? What about the Test.txt file?
$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
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?
I passed a string as an input for $1
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.