简体   繁体   English

将awk的结果放入数组中

[英]Put result of awk into an array

When I run the following command on terminal, 当我在终端上运行以下命令时,

awk /984/ $files | awk -F, '{OFS=",";print $1,$4,$17}'

where, 哪里,

files=`ls`

I get this output: 我得到这个输出:

2013/08/18 12:51:37,11,724
2013/08/18 12:48:02,227,84769

I wish to create a script, run that command and assign the above result to an array in this way: (Separate lines as separate elements) 我希望创建一个脚本,运行该命令并以这种方式将上述结果分配给数组:(将行分隔为单独的元素)

array[0] = 2013/08/18 12:51:37,11,724
array[1] = 2013/08/18 12:48:02,227,84769

BUT, 但,

neither, 都不是,

result=($(awk /string/ $files | awk -F, '{OFS=",";print $1,$4,$17}'))

nor, 也不,

result2=`awk /string/ $files | awk -F, '{OFS=",";print $1,$4,$17}'`

fulfills my purpose. 实现我的目的。

How to get an array like I specified? 如何获得像我指定的数组?

When you say: 当你说:

result=($(awk /string/ $files | awk -F, '{OFS=",";print $1,$4,$17}'))

the output would be split by whitespace. 输出将按空格分割。 Set IFS to a newline character, and you should see the desired result. IFS设置为换行符,您应该看到所需的结果。 Say: 说:

IFS=$'\n' result=($(awk /string/ $files | awk -F, '{OFS=",";print $1,$4,$17}'))

instead to capture different lines of output into an array. 而是将不同的输出捕获到数组中。

To store variables in an array, output needs to be in a form like this: 要将变量存储在数组中,输出必须采用如下形式:

result=$(one two "more data")
echo ${result[2]}
more data

Data separated by spaces. 数据用空格分隔。 So tweak your output to give that format. 所以调整输出以提供该格式。

Can you give an example of what you get out of: 你能举例说明你的成就:

awk '/984/' $files | awk -F, '{OFS=",";print $1,$4,$17}'

It may be shorten to: 它可能缩短为:

awk -F, '/984/ {OFS=",";print $1,$4,$17}' $files

I think the problem is in the usage of () in your script. 我认为问题在于脚本中使用()。 I tried a similar example and got the required output 我尝试了一个类似的例子并获得了所需的输出

myarray=(`ls *.sh`)
for f in ${myarray[@]} 
do
    echo $f
done

I think the code of yours should be changed as follows 我认为你的代码应该改变如下

result=(`awk /string/ $files | awk -F, '{OFS=",";print $1,$4,$17}'`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM