简体   繁体   中英

how to pass the filename as variable to a awk command from a shell script

in my shell script i have the following line

PO_list=$(awk -v col="$1" -F";" '!seen[$col]++ {print $col}' test.csv)

which generates a list with the values from column "col" which came from "$1" from file test.csv. it might be possible to have several files in same location and for this would need to loop among them with a for sentence. For this I have to replace the filename test.csv with a variable, $i for example, which is the index from the list of files.

trying to fulfill my request, I was modifying my line with

PO_list=$(awk -v col="$1" -F";" '!seen[$col]++ {print $col}' $j)

unfortunately, i receive the error message:

awk: cannot open test.csv (No such file or directory)

Can anyone tell me why this error occur and how can I solve it, please?

Thank you,

As you commented in your previous question, you are calling it with

abc$ ./test.sh 2

So you just need to add another parameter when you call it:

abc$ ./test.sh 2 "test.csv"

and the script can be like this:

PO_list=$(awk -v col="$1" -F";" '!seen[$col]++ {print $col}' "$2")
#                                                            ^^^^

Whenever you want to use other parameters, remember they are positional. Hence, the first one is $1 , second is $2 and so on.

In case the file happens to be in another directory, you can replace ./test.sh 2 "test.csv" by something like ./test.sh 2 "/full/path/of/test.csv" or whatever relative path you may need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM