user1947569
user1947569

Reputation: 23

Passing bash input variables to awk

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

Upvotes: 2

Views: 33507

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125798

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

Upvotes: 8

perreal
perreal

Reputation: 97948

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}'

Upvotes: 2

Related Questions