Bash – Loop through file and make every word a variable

bashosx

I have a text file that looks like this:

1923.12.312. Nikl
12391.123.123 Jo
12398123.123912 Ad

I am trying to loop through this file, and make 1923.12.312. variable1, and Nikl variable2 then use those in an echo command. Then it should continue and make 12391.123.123 variable1 and Jo variable2 and echo those etc.

So far, this is what I've done:

while read p
do 
variable1="$(awk '{print $1}')"
variable2="$(awk '{print $2}')"
echo "if [ \"\$STATUS\" == \"$variable1\" ]
then
vem=\"$variable2\"
fi"
done saker.txt

And that's supposed to put out:

if [ "$STATUS" == "1923.12.312." ]
then
vem="NIKL"
fi

etc. But it doesn't, instead, this is the output

awk: cmd. line:1: {print $2)
awk: cmd. line:1:          ^ syntax error
if [ "STATUS" == "12391.123.123
12398123.123912" ]
then
vem=""
fi

I also tried ditching the variables and did this instead:

while read p
do 
echo "if [ \"\$STATUS\" == \"`awk '{print $1}'`\" ]
then
vem=\"`awk '{print $2}'`\"
fi"
done saker.txt

But it produced the same result.

Best Answer

Using shell

If we use the ability of read to separate lines into variables and it is quite easy:

while read var1 var2
do
    echo "if [ \"\$status\" == \"$var1\" ]
then
vem=\"$var2\"
fi"
done <saker.txt

This produces:

if [ "$status" == "1923.12.312." ]
then
vem="Nikl"
fi
if [ "$status" == "12391.123.123" ]
then
vem="Jo"
fi
if [ "$status" == "12398123.123912" ]
then
vem="Ad"
fi

Using awk:

This awk command uses a single printf command:

$ awk '{printf "if [ \"$status\" == \"%s\" ]\nthen\nvem=\"%s\"\nfi\n",$1,$2}' saker.txt
if [ "$status" == "1923.12.312." ]
then
vem="Nikl"
fi
if [ "$status" == "12391.123.123" ]
then
vem="Jo"
fi
if [ "$status" == "12398123.123912" ]
then
vem="Ad"
fi