Tiny Core Linux
General TC => Programming & Scripting - Unofficial => Topic started by: sbp on May 21, 2014, 04:10:48 PM
-
Hi I need help in making a script where I will read from a txt file.
In this file each line should be read and saved as a new variable like var1, var2 etc.
I have tried this code:
#!/bin/sh
while read LINE
do
var1=$(echo $LINE)
echo $var1
var
done < FILE.txt
This will read the file (FILE.txt) and list the content of each line on the screen, but I need to assign each line to a new variable.
The content of FILE.txt
CONTENT_A
CONTENT_B
CONTENT_C
etc
And the output I would like would be:
var1=CONTENT_A
var2=CONTENT_B
var3=CONTENT_C
etc..
Thanks
Steen
-
Try a bash forum.
What you want to do is extremely difficult.
-
The following seems clumsy, but it works. I hate having to use temp files, but I suspect there's a more elegant way.
# create a data file for testing
echo -e "Value A\nValue B\nValue C" >/tmp/datfile
# initialize the variable part of the variable name
VARVAR=0
# read the data and write a temp file
cat /tmp/datfile |while read X ; do {
echo "VAR${VARVAR}=\"${X}\"" >>/tmp/dotme
VARVAR="`expr ${VARVAR} + 1`"
} done
# source the temp file
. /tmp/dotme
# demonstrate that it worked
echo -e "VAR0=${VAR0}\nVAR1=${VAR1}\nVAR2=${VAR2}"
-
Another temp file fudge using your input file format.
awk '{ print "var"NR"="$0 }' FILE.txt > temp.sh && . temp.sh
regards
-
Hi sbp
If you provided some more details on exactly what you are trying to do, someone might be able to offer a better solution. In the mean
time, try doing a Google search for:
linux script dynamic array
-
Another temp file fudge using your input file format.
awk '{ print "var"NR"="$0 }' FILE.txt > temp.sh && . temp.sh
regards
Hi Greg
Thank you for your suggestion it is working fine. I need it for allowing update of piCorePlayer in situ.
I might be needing more help, but I'm trying to get it working.
Steen
-
Another temp file fudge using your input file format.
awk '{ print "var"NR"="$0 }' FILE.txt > temp.sh && . temp.sh
regards
Hi Greg
Thank you for your suggestion it is working fine. I need it for allowing update of piCorePlayer in situ.
I might be needing more help, but I'm trying to get it working.
Steen
Hi Steen,
Happy to help if I can. Ironically I only knew an answer because I have been going over your piCorePlayer scripts.
regards
-
If using bash, an array seems best to me:
while read line; do
vars[${#vars[*]}]="$line"
done </path/to/file
Else use eval:
cpt=0
while read line; do
cpt=`expr $cpt + 1`
eval "var${cpt}=\"\$line\""
done </path/to/file