简体   繁体   中英

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.

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+):

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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