bash 如何将变量传递给 awk 命令行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40177687/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:19:51  来源:igfitidea点击:

how to pass in a variable to awk commandline

bashshellawk

提问by user3799576

I'm having some trouble passing bash script variables into awk command-line.

我在将 bash 脚本变量传递到 awk 命令行时遇到了一些麻烦。

Here is pseudocode:

这是伪代码:

for FILE in $INPUT_DIR/*.txt; do
 filename=`echo $FILE | sed -n 's/^.*\(chr[0-9A-Z]*\).*.vcf$//p'`
 OUTPUT_FILE=$OUTPUT_DIR/$filename.snps.txt
 egrep -v "^#" $FILE | awk '{print ,,}' > $OUTPUT_FILE
done

The final line where I awk the columns, I would like it to be flexible or user input. For example, the user could want columns 6,7,and 8 as well, or column 133 and 138, or column 245 through 248. So how do I custom this so I can have that 'print $2 .... $5' be a user input thing? For example the user would run this script like : bash script.sh input_dir output_dir [user inputs whatever string of columns], and then I would get those columns in the output. I tried passing it in, but I guess I'm not getting the syntax right.

我对列进行 awk 的最后一行,我希望它是灵活的或用户输入。例如,用户可能还需要第 6,7 和 8 列,或第 133 和 138 列,或第 245 至 248 列。那么我如何自定义它,以便我可以让“打印 $2 .... $5”成为用户输入的东西?例如,用户会像这样运行这个脚本:bash script.sh input_dir output_dir [用户输入任何列的字符串],然后我会在输出中得到这些列。我尝试传入它,但我想我的语法不正确。

采纳答案by Michal Krzyz

The following test works for me:

以下测试对我有用:

A="$3" ; ls -l | awk "{ print $A }"

回答by aherrero

With awk, you should declare the variable before use it. This is better than the escape method (awk '{print $'$var'}'):

使用 awk,您应该在使用之前声明变量。这比转义方法更好(awk '{print $'$var'}'):

awk -v var1="$col1" -v var2="$col2" 'BEGIN {print var1,var2 }'

Where $col1 and $col2 would be the input variables. Maybe you can try an input variable as string with "$2,$4,$5" and print this variable to get the values (I am not sure if this works)

其中 $col1 和 $col2 将是输入变量。也许您可以尝试将输入变量作为带有 "$2,$4,$5" 的字符串并打印此变量以获取值(我不确定这是否有效)