0

I am trying to store values of the first line of a text file into an array. Here is what I have so far:

arr_values=()

awk '
    NR==1 {
            for (i=0; i<=NF; i++)
               'arr_values[i]'=$i
          }' file.txt

for ((i=0; i<${#arr_values[@]}; i++))
do
   echo arr_values[i]
done

I am getting an error with initializing the array mainly because I don't know how to use awk to initialize an external array. Any suggestions (only with awk)? Thanks.

2 Answers 2

2

You can do this:

read -a array <<< $(head -n 1 file)

echo ${array[0]}
echo ${array[1]}
Sign up to request clarification or add additional context in comments.

6 Comments

What is difference between my solution? Expect of process substitution which is not required here.
No seriously, your pipe starts a subshell which is ephemeral.
I am not sure what is really going on, but I know if I do command | while read x; do array[0]=x; done it never works as part of a pipe and the same thing is happening here.
You were right! It was a problem with my tests. I'm sorry for the confusion.
You could replace <<< $(head -n 1 file) by <<< $(awk 'NR==1 {print;exit}' file). Also dogbane's answer could be modified to use awk : arr=($(awk 'NR==1{print;exit}' file)). However, the head statement is perfect here.
|
1

You probably can simply just do

read -ra arr_values < file.txt

Which would only process the first line and split it uniformly like awk does; saving it into arr_values. No need to fork with external binary commands.

2 Comments

why \t? The OP hasn't specified that and by default awk splits on whitespace.
@dogbane I don't always remember that. Just tested it and found out that I was wrong so I made the edit just some seconds before you made the comment.

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.