Put result of awk into an array

ⅰ亾dé卋堺 提交于 2019-12-04 04:21:20

问题


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?


回答1:


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. Say:

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

instead to capture different lines of output into an array.




回答2:


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



回答3:


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}'`)


来源:https://stackoverflow.com/questions/21130417/put-result-of-awk-into-an-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!