0

naam$var='value' doesn't work

Need to use it in a loop : naam$var=$(sed -n $var"p" namefile.txt)

Dynamic variable names in Bash doesn't do the trick for me. Maybe i didn't understand it inuff, but I already spend time on this. For me it just doesn't work it.

I hope to find someting that works, and is not to long, or complex. And if the loop works, my script should be smaller, faster and smoking enter image description here

# To create example file 'naam.txt' echo "John " > naam.txt echo "Susan " >> naam.txt echo "Nicole " >> naam.txt echo "Betsy " >> naam.txt

    # This works for me now
    naam1=$(sed -n 1"p"  naam.txt)
    naam2=$(sed -n 2"p"  naam.txt)
    naam3=$(sed -n 3"p"  naam.txt)
    naam4=$(sed -n 4"p"  naam.txt)
    echo $naam1 
    echo $naam3
    echo $naam2
    echo $naam4

    # But i want to use it in a for loop. 
    # '$var' will be used twice in one line
    # 'naam$var=value' doesn't work
    for var in 1 2 3 4 
    do
        naam$var=$(sed -n $var"p"  namefile.txt)
    done
    echo $naam1 $naam4

Solved

I found this solution with to links from https://stackoverflow.com/users/4154375/pjh Thanks pjh Most from: Creating a string variable name from the value of another string And 1 line from: How can I generate new variable names on the fly in a shell script? I used it like this:

num=5                                               # amount of names you need.
for (( i = 1; i <= $num; i++ ))                     
do
    CONFIG_OPTION="naam$i"                          # Name of new variable
    CONFIG_VALUE=$(sed -n $i"p"  naam.txt)          # value of new variable
    printf -v "$CONFIG_OPTION" "%s" "$CONFIG_VALUE" # magic happens here
done

#creat a testfile
echo "John   " > naam.txt
echo "Susan  " >> naam.txt
echo "Nicole " >> naam.txt
echo "Betsy  " >> naam.txt
# create some output to see of it works
echo "1     $naam1"
echo "2     $naam2"
echo "3     $naam3"
echo "4     $naam4"
echo "5     $naam5"
echo "6     $naam6"
  • Also see [how can i generate new variable names on the fly in a shell script?](https://stackoverflow.com/questions/10820343/how-can-i-generate-new-variable-names-on-the-fly-in-a-shell-script), [Creating a string variable name from the value of another string](https://stackoverflow.com/questions/13716607/creating-a-string-variable-name-from-the-value-of-another-string), and [BashFAQ/006 (How can I use variable variables (indirect variables, pointers, references) or associative arrays?)](https://mywiki.wooledge.org/BashFAQ/006). – pjh Jul 03 '23 at 12:53
  • Also note that you can post an answer to your question. Don't edit the question to include the answer, stackoverflow has a fairly strict separation of questions and answers. – Robert Jul 03 '23 at 18:34
  • thanks Robert, i couldn't find where to answer my question. – user20589826 Jul 03 '23 at 20:18

0 Answers0