Linux - awk中的readarray

时间:2014-08-25 10:15:02

标签: linux awk

我是shell scritpts的新手。我正在尝试使用readarray加载单列文件(column1 - 数字)并打印数组的长度。但是得到了错误。

GNU bash,版本4.1.2(1)-release(x86_64-redhat-linux-gnu)

array.sh

sqlplus -s user/pass@SID.WORLD <<-END > /dev/null

set heading off;
spool /tmp/numbers.txt
select number from table;
COMMIT;
spool off;
END


awk '{
        readarray tn < "/tmp/numbers.txt"
        print $1     #// just checking
        print  ${#tn[@]}   #// getting array length.
}' /tmp/numbers2.txt

错误:

awk: cmd. line:3:       print  ${#tn[@]}
awk: cmd. line:3:               ^ syntax error

更新

I want to use that readarray to populate array and do some operation on array.

如果我将awk更改为

awk  '{
        readarray tn < "/tmp/numbers.txt"
        print tn;    # // will print blank lines that is equals to actual lines of file
}' /tmp/numbers1.txt

2 个答案:

答案 0 :(得分:2)

一些替代方案:

只需使用bash:readarray tn < "/tmp/numbers.txt"; echo ${#tn[@]}

awk:awk 'END {print NR}' /tmp/numbers.txt

wc:wc -l < /tmp/numbers.txt

SQL:

set heading off;
spool /tmp/numbers.txt
select number from table;
spool off;
select count(number) from table;

答案 1 :(得分:1)

awk不是shell。 readarray是一个shell命令。 ${#tn[@]}是一个shell变量评估。这些都不是在awk中有效。

我并不清楚你要做什么,所以我不能真正开始建议正确的做法。