1

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

3
  • 2
    Why do you need to store awk output in a shell array? Is it not possible to use awk for all the data processing? Commented Sep 16, 2019 at 14:25
  • You'll need to assign those values to indexed arrays, i.el arr[0]="Site is facebook". Good luck. Commented Sep 16, 2019 at 14:26
  • Based on items in array, need to perform further actions... Commented Sep 16, 2019 at 14:26

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.