LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Creating array from command output (bash shell script) (https://www.linuxquestions.org/questions/programming-9/creating-array-from-command-output-bash-shell-script-858821/)

Rizla 01-26-2011 11:54 AM

Creating array from command output (bash shell script)
 
Hi, I have a command that outputs n lines of text, and I want to place each line into an array element, but I can't seem to get the syntax correct

so my command is this:
cat $configfile | sed -n '/cluster:'$clustername'/,/cluster/ p' | awk /host/

which produces many lines depending on the value of $clustername. I'd like to get each line as elements of an array,

any help would be much appreciated,

Thanks

crts 01-26-2011 12:42 PM

Quote:

Originally Posted by Rizla (Post 4238452)
Hi, I have a command that outputs n lines of text, and I want to place each line into an array element, but I can't seem to get the syntax correct

so my command is this:
cat $configfile | sed -n '/cluster:'$clustername'/,/cluster/ p' | awk /host/

which produces many lines depending on the value of $clustername. I'd like to get each line as elements of an array,

any help would be much appreciated,

Thanks

Hi,

you also need to fix your sed statement and the excessive piping.
Code:

#!/bin/bash
declare -a ARRAY
count=0
while read -r line; do
  var[((count++))]="$line"
done < <(sed -n "/cluster:$clustername/,/cluster/ {/host/ p}" "${configfile}")


everToulouse 01-26-2011 02:54 PM

Code:

#!/bin/bash

configfile=/path/to/file
clustername=whatever

while read -r line
do
  [[ $line =~ cluster ]] && flag=0

  [[ $line =~ cluster:${clustername} ]] && flag=1

  if ((flag)) && [[ $line =~ host ]]; then Array+=("$line"); fi

done < "${configfile}"

printf '%s\n' "$Array[@]}"

I prefer not use external commands when I can avoid them.
without a representative sample of $configfile, it's hard to do better.
perhaps it's posible to do it without regexes.

colucix 01-26-2011 03:10 PM

Another way is by setting the IFS variable to newline only (and restore it to the default later). Following the suggestion by crts:
Code:

OLD_IFS=${IFS}
IFS=$'\n'
ARRAY=( $(sed -n "/cluster:$clustername/,/cluster/ {/host/ p}" "${configfile}") )
IFS=${OLD_IFS}


grail 01-26-2011 06:53 PM

@everToulouse - your Array is a string and not an Array. Try changing @ for a 1 and you will see there is no value stored there. Easy fix though, throw in some
brackets and your all good:
Code:

if ((flag)) && [[ $line =~ host ]]; then Array+=("$line"); fi

everToulouse 01-26-2011 10:47 PM

Hi grail,

oops!
corrected, thx.


All times are GMT -5. The time now is 01:34 PM.