rkmax
rkmax

Reputation: 18133

Bash: Assign many variables in one operation

I have a file like

line1 word1 word2 word4 etc..
line2 word1 word2 word4 etc..

I know I can extract words with cut -d ' ' -fx command but I want to extract and assign many words in one operation.

while read line;do
  echo $line | awk '{ word1=$1; word2=$2 }'
  # usage $word1, $word2, etc.
done < $file 

Is this possible?

Better example

file
jose  1234 2011/12/01
maria 2345 2010/04/10
script
while read line;do
  echo $line | awk '{ name=$1; counter=$2, date=$3 }'
  # usage $name, $counter, $date, etc
done < $file 

Upvotes: 0

Views: 1287

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 754540

If the number of words in a line is fixed (the easy case), then:

while read name number date
do
    # ...use $name, $number, $date
done <<'EOF'
jose  1234 2011/12/01
maria 2345 2010/04/10
EOF

Note that if there are 4 or more words in the line, $date will get all the remaining words after the name and number. If there are fewer than three, the read will work but the variables without a value (date or number or even name) will be empty strings.

If the number of words in a line is variable, then you probably want to use bash arrays with read:

while read -a array
do
    # ...process "${array[@]}"...
    echo "${array[@]}"
done <<'EOF'
one
two three
four five six
seven eight
nine
EOF

Upvotes: 6

peteches
peteches

Reputation: 3629

It's possible using awk

root@server$ vars=$( awk '{for(i=1;i<=NF;i++){ print "word" i "=" $i }}' file )
root@server$ echo $vars
word1=one word2=two word3=three
root@server$ declare $vars
root@server$ echo $word1 
one

So the breakdown

Awk has in internal variable NF which is the number of fields in the line. So we run a quick for loop iterating over all the fields, skipping field 0 as thats the whole line. for each iteration we print out a bash variable assignment statement and capture the output into the vars variable.

we then use declare to declare the variables. If we don't use declare then we are executing some arbitary code in a file.

Hope this is usefull.

Upvotes: 3

Related Questions