简体   繁体   中英

How can I read a file line by line and redirect each line to a variable in shell scripting?

I am using ksh shell. I want to use those variables and get the values when I call (p1,p2,p3,p4). The file test1.log may contain any number of lines hence cannot define it as p1...p4. The script itself should consider the number of lines and assign variables accordingly in sequence.

Please help on this. Below is my input file test1.log

ABC
DEF
GHI
JKL    

I want my output as

p1=ABC
p2=DEF
p3=GHI
p4=JKL    

You may leverage the -n option of cat which plots the line numbers. With some Perl substitution afterwards, a simple solution would be :

$ cat -n test1.log | perl -pe 's/^(\s*)(\d+)(\s*)/p$2=/'
p1=ABC
p2=DEF
p3=GHI
p4=JKL

If you want to access those variables within a script, I suggest you use the eval command the following way :

while read line; do
  eval "$line" ;
done < <(cat -n tmp | perl -pe 's/^(\s*)(\d+)(\s*)/p$2="/; s/$/"/')

echo p1 : $p1
echo p2 : $p2

Note that in this second example, I added the support for lines where you have spaces inside by adding double quotes around. I use the following input file :

$ cat test1.log
ABC foo
DEF
GHI
JKL

Directly from the command line, you can of course run the while part and get p1,p2,... available in the shell.

If you want to "load" the variables separately and access them inside other scripts, you may use the export command (I prefer to add it in the Perl substitution part) :

while read line; do eval "$line" ; done < <(cat -n tmp | perl -pe 's/^(\s*)(\d+)(\s*)/export p$2="/; s/$/"/')

After running this command in the shell, a simple script like

$ cat tmp.sh
echo p1 : $p1
echo p2 : $p2
echo p3 : $p3
echo p4 : $p4

will then output

$ ./tmp.sh
p1 : ABC foo
p2 : DEF
p3 : GHI
p4 : JKL

Enjoy

vars=`cat data.txt`

inc=0
for v in ${vars}
do
        inc=`expr $inc + 1`
        declare "param$inc=$v";
        localParam="param$inc"
        echo "${localParam}=${!localParam}";
done

In ksh, you can use eval like this

cat $file |
  while read LINE 
  do  
    for out in $LINE  
    do  
      eval part$((++i))="$out" 
    done 
  done
echo "p1=$part1"
echo "p2=$part2"
echo "p1=$part3"
echo "p4=$part4"

I have also changed i++ to ++i so that indexing starts at 1 rather than 0.

如果您的输入数据确实不包含任何空格字符,则可以使用

grep -v '^$' YOURFILE | nl -s= -w99 | tr -s ' ' p

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM