如何将文件名作为变量传递给shell脚本中的awk命令

时间:2021-09-24 19:24:15

in my shell script i have the following line

在我的shell脚本中,我有以下行

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.

它生成一个列表,其中包含来自文件test.csv的“$ 1”列中的值“col”。也许有可能在同一个位置有几个文件,因此需要用句子循环它们。为此,我必须用变量$ i替换文件名test.csv,例如,这是文件列表中的索引。

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)

awk:无法打开test.csv(没有这样的文件或目录)

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

任何人都可以告诉我为什么会出现这种错误,我该如何解决呢?

Thank you,

谢谢,

1 个解决方案

#1


2  

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.

每当您想使用其他参数时,请记住它们是位置的。因此,第一个是1美元,第二个是2美元,依此类推。

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.

如果文件碰巧在另一个目录中,你可以用./test.sh 2“/full/path/of/test.csv”或任何相对路径替换./test.sh 2“test.csv”你可能需要。

#1


2  

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.

每当您想使用其他参数时,请记住它们是位置的。因此,第一个是1美元,第二个是2美元,依此类推。

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.

如果文件碰巧在另一个目录中,你可以用./test.sh 2“/full/path/of/test.csv”或任何相对路径替换./test.sh 2“test.csv”你可能需要。