Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi
I have a .dat file named say file.dat it contains something like this
Build_ver=CTM_4_0_0
Build_No=101
Patch=1i want to open this .dat file from shell script and i want the values to be assigned to another 3 diff variables?
how should i do it
Appreciate your help

Use nawk:
VAR1=`nawk -F= '{if(NR==1)print $2}' info.dat`
VAR2=`nawk -F= '{if(NR==2)print $2}' info.dat`
VAR3=`nawk -F= '{if(NR==3)print $2}' info.dat`echo $VAR1 --> CTM_4_0_0
echo $VAR2 --> 101
echo $VAR3 --> 1-jim

Don't need nawk. Just put them in an array. I put your example data in a file called junk.dat.
Jerry
#!/bin/ksh
exec 3< junk.dat
counter=1
while [ $counter -le 3 ]
do read -u3 Line
var[$counter]=$Line
((counter += 1))
done
counter=1
while [ $counter -le 3 ]
do
print ${var[$counter]}
(( counter += 1 ))
done

That last solution does not reassign the variables to different variable names. It loads entire lines into an array, then prints those entire lines from the array. The same results can be accomplished with:
cat junk.dat
I offer two solutions. The first, same as jimbo, reassigns to sequentially numbered var1, var2, etc, in whatever order the input is in. But instead of using awk, I use read like Jerry, except that I delimit the incoming fields with an equal-sign so I can get to the second field:
#!/bin/ksh
k=1
cat file.dat |
while IFS="=" read word1 word2
do
eval var$k=$word2
((k=k+1))
done
print var1=$var1
print var2=$var2
print var3=$var3
exit 0But this second solution should be more useful. It looks for the old variable names of interest, then reassigns the assigned value to corresponsing new variable names. Lines not of interest will be ignored:
#!/bin/sh
cat file.dat |
while IFS="=" read word1 word2
do
case $word1 in
Build_ver) myver=$word2;;
Build_No) myno=$word2;;
Patch) mypatch=$word2;;
esac
done
print myver=$myver
print myno=$myno
print mypatch=$mypatch
exit 0

Would have been a trival exercise to put them into different variables. Thought the array was sufficient. There is absolutely nothing wrong with the provided solution.

![]() |
Chmod question?
|
network driver
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |