tags:

views:

198

answers:

4

Is it possible to load new lines from a text file to variables in bash?

Text file looks like?

EXAMPLEfoo 
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

Variables become

$1 = EXAMPLEfoo 
$2 = EXAMPLEbar 

ans so on?

+2  A: 
cat somefile.txt| xargs bash_command.sh

bash_command.sh will receive these lines as arguments

Андрей Костенко
+1  A: 

This can be done be with an array if you don't require these variables as inputs to a script. push() function lifted from the Advanced Scripting Guide

push()            # Push item on stack.
{
if [ -z "$1" ]    # Nothing to push?
then
  return
fi

let "SP += 1"     # Bump stack pointer.
stack[$SP]=$1

return
}

The contents of /tmp/test

[root@x~]# cat /tmp/test
EXAMPLEfoo
EXAMPLEbar
EXAMPLE1
EXAMPLE2
EXAMPLE3
EXAMPLE4

SP=0; for  i in `cat /tmp/test`; do push $i ; done

Then

[root@x~]# echo ${stack[3]}
EXAMPLE1
Andy
+6  A: 
$ s=$(<file)
$ set -- $s
$ echo $1
EXAMPLEfoo
$ echo $2
EXAMPLEbar
$ echo $@
EXAMPLEfoo EXAMPLEbar EXAMPLE1 EXAMPLE2 EXAMPLE3 EXAMPLE4
ghostdog74
neat. the rest of this comment is filler :)
Andy
+1  A: 
saveIFS="$IFS"
IFS=$'\n'
array=($(<file))
IFS="$saveIFS"
echo ${array[0]}    # output: EXAMPLEfoo 
echo ${array[1]}    # output: EXAMPLEbar
for i in "${array[@]}"; do echo "$i"; done    # iterate over the array

Edit:

The loop in your pastebin has a few problems. Here it is as you've posted it:

for i in "${array[@]}"; do echo "  "AD"$count = "$i""; $((count=count+1)); done

Here it is as it should be:

for i in "${array[@]}"; do declare AD$count="$i"; ((count=count+1)); done

or

for i in "${array[@]}"; do declare AD$count="$i"; ((count++)); done

But why not use the array directly? You could call it AD instead of array and instead of accessing a variable called "AD4" you'd access an array element "${AD[4]}".

echo "${AD[4]}"
if [[ ${AD[9]} == "EXAMPLE value" ]]; then do_something; fi
Dennis Williamson
Would I be asking for a world of pain to try define the variables in the loop? Like this http://pastebin.com/MqGiS8WK
S1syphus
@S1syphus: see my edit.
Dennis Williamson