简体   繁体   English

将awk输出存储在bash数组中的问题

[英]Issue storing awk output in bash array

I have below file: 我有以下文件:

Site is facebook.
Site is microsoft.
Site is google.

And below script: 和下面的脚本:

#!/bin/bash

#tried arr=$(awk {'print'} test) which gives array length as 1

arr=($(awk {'print'} test))


echo "Length ::: ${#arr[@]}"

Here the expected output is 3. However, I am getting length of array as 9. Above is just an excerpt from a script and need to use awk here. 此处的预期输出为3。但是,我得到的数组长度为9。上面只是脚本的摘录,需要在此处使用awk。

Please let me know where the issue is.... 请让我知道问题出在哪里....

This is the correct way to build a shell array of one entry per line from output of awk (requires bash 4+): 这是从awk的输出构建每行一个条目的shell数组的正确方法(需要bash 4+):

readarray -t arr < <(awk '1' file)
declare -p arr

declare -a arr=([0]="Site is facebook." [1]="Site is microsoft." [2]="Site is google")

When you use this code: 使用此代码时:

arr=($(awk '1' file))

Then shell splits on default delimiter and assigns each word from awk output to a separate array entry. 然后,shell在默认定界符上分割,并将awk输出中的每个单词分配给单独的数组条目。

Having said that please bear in mind that awk is capable of doing everything that shell can do and it is always better to process your data in awk itself. 话虽如此,请记住awk能够执行shell可以做的所有事情,并且始终最好在awk自身中处理数据。

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

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