3

Trying to pass a variable into awk from user input:

Have tried variations of awk -v with errors stating 'awk: invalid -v option', even though the option is listed in man files.

#! /bin/bash
read -p "Enter ClassID:" CLASS
read -p "Enter FacultyName:" FACULTY


awk '/FacultyName/ {print}' data-new.csv > $FACULTY.csv
awk -vclass=${CLASS} '/class/ {print}' data-new.csv >> $FACULTY.csv 


echo Class is $CLASS
echo Faculty member is $FACULTY
3

2 Answers 2

9

Some versions of awk require a space between the -v and the variable assignment. Also, you should put the bash variable in double-quotes to prevent unwanted parsing by the shell (e.g. word splitting, wildcard expansion) before it's passed to awk. Finally, in awk /.../ is a constant regular expression (i.e. /class/ will search for the string "class", not the value of the variable "class"). With all of this corrected, here's the awk command that I think will do what you want:

awk -v class="${CLASS}" '$0 ~ class {print}' data-new.csv >> $FACULTY.csv

Now, is there any reason you're using this instead of:

grep "$CLASS" data-new.csv >> $FACULTY.csv
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Gordon, it worked. I am very new to programming with awk and bash, the learning curve is a bit steep for me but this helps move my knowledge along. The grep command I have some experience, however, I am still enough of a newbie not to know the best method, at the very least, I wanted to learn about awk. Thanks to everyone else for replying.
2

Your script is not clear to me, but these all work:

CLASS=ec123
echo | awk -vclass=$CLASS '{print class}'
echo | awk -vclass=${CLASS} '{print class}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.