Karl
Karl

Reputation: 3372

Failure to populate Bash array from AWK statement

I need to get 1 or more locations from a config file and then check each location for some files. I have an AWK and SED combination which finds the locations and then read the list of files from a text file. I want to check each location for the file and thought to use a bash array to hold the locations.

However for some reason I cannot populate the array from the AWK statement. It appears to me that it loads the complete content into the first element.

If I manually populate the array it works; e.g. replace the line array=$(awk ... with

array[1]=/docs01/objdata/admin/p1dig
array[2]=/docs02/objdata/admin/p1dig
array[3]=/docs03/objdata/admin/p1dig
array[4]=/docs04/objdata/admin/p1dig

In the code snippet below I have removed the outer (filename) loop and added some debugging context.

#!/bin/bash

declare -a array

OBJECTIVE_CONF=/u01/app/objective/perf/DOS1/config/objConf.xml
FILE=/tmp/DoS1_files.dsv

# IFS=$"/n"
array=$(awk '/<volume>/,/<\/volume>/' $OBJECTIVE_CONF | grep "<path>" | sed "s#<[/]*path>##g" | sed 's/^[ \t]*//' |sed 's/[ \t]*$//' )

element_count=${#array[@]}
echo "element_count is : $element_count "


echo "index is: $index"
echo "${array[$index]}"

   echo "filename loop"

   index=0
   while [ "$index" -lt "$element_count" ]
   do
      let "index = $index + 1"
      echo "index is: $index"
      echo "ls ${array[$index]}/filename_from_loop"
   done
   echo "leaving loop"

The Awk statement gives me the expected result when run from the command line. I AWK for the start and finish XML tags, grep inside that for the PATH and use SED to remove the PATH exm tags and leading and training space.

bash-3.00$ awk '/<volume>/,/<\/volume>/' $OBJECTIVE_CONF | grep "<path>" | sed "s#<[/]*path>##g" | sed 's/^[ \t]*//' |sed 's/[ \t]*$//'
/docs01/objdata/admin/p1dig
/docs02/objdata/admin/p1dig
/docs03/objdata/admin/p1dig
/docs04/objdata/admin/p1dig

Upvotes: 1

Views: 528

Answers (2)

Farid
Farid

Reputation: 347

You can use the readarray statement too :

readarray array < <(command)

the differences than just assign, like array=($(<command>)), is that you have more control on the final array, (man)

the < <(command) is for function/command expansion without a child process.

Upvotes: 1

n. m. could be an AI
n. m. could be an AI

Reputation: 119877

$(<command>) substitution does not produce an array. To get an array, use another pair of parentheses:

array=($(<command>))

Upvotes: 3

Related Questions