将 Bash Shell 变量传递给 Awk NR 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33189178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing Bash Shell Variable to Awk NR function
提问by geeb.24
I wish to loop through a M row X N column array of values and print them to the screen to be used for a later script, but I am having trouble with the loop and NR. Here's what I have so far:
我希望遍历一个 M 行 XN 列值数组并将它们打印到屏幕上以供以后的脚本使用,但是我在循环和 NR 方面遇到了问题。这是我到目前为止所拥有的:
#!/bin/bash
cat temp_file | wc -l > num_rows
i="0"
while [ $i -le `cat num_rows` ]; do
echo $i
awk 'NR==$i{print , }' temp_file
awk 'NR==$i{print , }' temp_file
((i++))
done
As you can see, I wish to use first find the number of lines, num_rows, and loop through each of those rows, and use AWK's NR function to go through each row and print columns one and two first, then columns three and four. The following error results when the above script runs:
如您所见,我希望首先使用查找行数 num_rows 并遍历每一行,然后使用 AWK 的 NR 函数遍历每一行并首先打印第一和第二列,然后是第三和第四列。上述脚本运行时会出现以下错误:
0
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
2
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
3
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
awk: illegal field $(), name "i"
input record number 1, file temp_file
source line number 1
4
and so on until the while loop completes. Any thoughts on how to fix this script, because right now, setting NR==$i does not work. Thanks for the help.
依此类推,直到while循环完成。关于如何修复此脚本的任何想法,因为现在,设置 NR==$i 不起作用。谢谢您的帮助。
回答by slitvinov
You can pass i
to awk by
你可以传递i
给 awk
awk -v i=$i 'NR==i{print , }' temp_file
or
或者
awk 'NR=='$i'{print , }' temp_file