简体   繁体   中英

How to initialize an array using awk and bash?

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.

You can do this:

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

echo ${array[0]}
echo ${array[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.

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