Hi all,
I�m very new to UNIX programming. I have a question on dynamic variable
I�m having delimited file \(only one row\). First of all, I want to count number of columns based on delimiter. Then I want to create number of variables equal to number of fields.
Say number of fields equal to N
N=`cat ffvldtn_test.txt | awk 'BEGIN{FS="|"};{print NF}'`
From the above, I�m getting the fields count equal to five.
n=1
while [ $n -le $NF ];
do
eval "eval_var=\$var${n}"
eval_var=`cat ffvldtn_test.txt | cut -d '|' -f${n}`
echo "var${n}=${eval_var}"
((n=n+1))
done
The above script is working as expected. But the real thing is that I can�t re call the variables when I required in the script.
echo $var1
echo $var2
echo $var3
echo $var4
echo $var5
all are giving blank�
please help out to fix this
I guess "|" is your field separator, right?
try this:
read -a arr <<< `sed 's/|/ /g' | your_input_file_here`
for e in ${arr[@]}; do
echo $e
done
kevintse:
I guess "|" is your field separator, right?
try this:
read -a arr <<< `sed 's/|/ /g' | your_input_file_here`
for e in ${arr[@]}; do
echo $e
done
yes kevintse."|" is my field separator...thanks for ur reply...let u know if its work
---------- Post updated at 07:38 AM ---------- Previous update was at 07:32 AM ----------
kevintse,
its not at all working...better u chnage my code and post it...
Why don't you use arrays?
An example how to use arrays and "dynamic variables" if you persist to use that:
set $(awk 'BEGIN{FS="|"};{print NF}' ffvldtn_test.txt)
n=1
for i in $@
do
arr[$n]=${i} # fill array
eval "var_${n}=${i}" # fill dynamic variable
n=$(( $n + 1 ))
done
echo arr[1]
echo arr[2]
echo arr[3]
echo arr[4]
echo arr[5]
echo $var1
echo $var2
echo $var3
echo $var4
echo $var5
mkarthykeyan:
yes kevintse."|" is my field separator...thanks for ur reply...let u know if its work
---------- Post updated at 07:38 AM ---------- Previous update was at 07:32 AM ----------
kevintse,
its not at all working...better u chnage my code and post it...
Why, what error messages did you get?
can you run this code on your machine:
#!/bin/bash
read -a arr <<< `echo "hello|world|test" | sed 's/|/ /g'`
for e in ${arr[@]}; do
echo $e
done
#in my test, it prints
hello
world
test
$ sh test_1
test_1[2]: syntax error at line 2 : `<' unexpected