0

I want to grep a specific line for each loop in a for loop. I've already looked on the internet to see an answer to my problem, I tried them but it doesn't seem to work for me... And I don't find what I'm doing wrong.

Here is the code :

for n in 2 4 6 8 10 12 14 ; do
    for U in 1 10 100 ; do
        for L in 2 4 6 8 ; do
i=0
cat results/output_iteration/occ_"$L"_"$n"_"$U"_it"$i".dat
for k in $(seq 1 1 $L) ; do
        ${'var'.$k}=`grep "   $k    " results/output_iteration/occ_"$L"_"$n"_"$U"_it"$i".dat | tail -n 1`
done

which gives me :

%
%
%  site    density        double occupancy                
    1     0.49791021     0.03866179
    2     0.49891438     0.06077808
    3     0.50426102     0.05718336
    4     0.49891438     0.06077808
./run_deviation_functionL.sh: line 109: ${'var'.$k}=`grep "   $k    " results/output_iteration/occ_"$L"_"$n"_"$U"_it"$i".dat | tail -n 1`: bad substitution

Then, I would like to take only the density number, with something like:

 ${'density'.$k}=`echo "${'var'.$k:10:10}"  | bc -l`

Anyone knows the reason why it fails?

1 Answer 1

2

Use declare to create variable names from variables:

declare density$k="`...`"

Use the variable indirection to retrieve them:

var=var$k
echo ${!var:10:10}
Sign up to request clarification or add additional context in comments.

3 Comments

So if I understood well, I have to do declare var$k=grep " $k " file.dat | tail -n 1 ` ? But when I do this, I have this kind of error : ./run.sh: line 109: declare: 1': not a valid identifier ./run.sh: line 109: declare: 0.49791021': not a valid identifier ./run.sh: line 109: declare: `0.03866179': not a valid identifier
And when I do than var=var$k, echo $var ; it gives me "var1", "var2"... And not the line I wanted to grep
@B_runo: Double quote the ... if spaces are involved: declare var$k="`...`".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.