[英]AWK how to initialize a variable with multiple number of fields to print
I'm writing a SHELL script that will call an AWK script file printing specific fields based on the options specified by the user from the .sh script 我正在编写一个SHELL脚本,它将根据用户从.sh脚本指定的选项来调用AWK脚本文件,以打印特定字段
EXAMPLE
-N=field with a list of Names ==> is the filed number 2
-A=field with a list of Addresses ==> is the filed number 4
-P=field with a list of Prices ==> is the field number 6
-D=field with a list of Dates ==> is the field number 10
./SHELLSCRIPT.sh -N -A -P -D
NAMES,ADDRESSES,PRICES,DATES
NAMES,ADDRESSES,PRICES,DATES
NAMES,ADDRESSES,PRICES,DATES
EXAMPLE 例
./SHELLSCRIPT.sh -N -D
NAMES,DATES
NAMES,DATES
NAMES,DATES
I'm trying to initialize a variable inside AWK using the -v option passing the number of fields but I'm having some difficulties on printing it... 我正在尝试使用-v选项通过传递字段数来初始化AWK中的变量,但在打印时遇到一些困难...
here is the AWK script: 这是AWK脚本:
#!/usr/bin/awk -f
BEGIN {
FS="\",\"" ;
-v test=2,4,6,10
for (i in test)
print $test[i];
}
AWK script must exclude some field/s when the user doesn't specify some option/s in the shell script 当用户未在Shell脚本中指定某些选项时,AWK脚本必须排除某些字段
Thanks in advance for your attention and support. 在此先感谢您的关注和支持。
-v
is an awk ARGUMENT, not a language construct. -v
是awk参数,而不是语言构造。 It's something you specify on the awk command line, like -F
. 这是您在awk命令行上指定的,例如-F
。 Nevere use a shebang to invoke awk from a script as it just takes away from available functionality. 决不要使用shebang从脚本中调用awk,因为它只是剥夺了可用功能。 Instead of what you had: 而不是你有:
#!/usr/bin/awk -f
BEGIN {...}
you'd do this: 您可以这样做:
/usr/bin/awk '
BEGIN {...}
' "$@"
which then lets you use awk args, access shell positional parameters, exported variables, etc. as you like, eg: 然后,您可以根据需要使用awk args,访问shell位置参数,导出的变量等,例如:
/usr/bin/awk -v test='2,4,6,10' '
BEGIN {...}
' "$@"
Now, to address your actual problem you'd write: 现在,要解决您的实际问题,您需要编写:
/usr/bin/awk -F'"," -v test='2,4,6,10' '
BEGIN {
split(test,array1,/,/)
for (i in array1)
array2[array1[i]]
}
{
print "array1:"
for (i=1; i in array1; i++) {
print i, $(array1[i])
}
print "array2:"
for (i in array2) {
print i, $i
}
}
' "$@"
array1 would be what you use when you do care about the order in which the fields are output, array2 would be when you don't care about the order. 当您关心字段的输出顺序时,将使用array1;而当您不在乎顺序时,将使用array2。
Maybe this wil help: 也许这会有所帮助:
awk -v bozo=12 -v brains=99 'BEGIN{print bozo,brains}' /dev/null
12 99
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.