user103185
user103185

Reputation: 1175

Assign lines in a text to individual variables (sh or bash, arrays not supported)

I use the dialog command to prompt the user for input. The result is a text with on each line a value corresponding to the fields.

I want to assign each line back to the variable corresponding to the field. This way I can easily construct control flow and an .ini type of file.

So if I have a form with 3 fields A, B and C, the text in $RESULTS would be: "aaa\nbbb\nccc\n". And I want:

$varA to be 'aaa'
$varB to be 'bbb'
$varC to be 'ccc'

The alternative seems to be the paste command, but as I need to verify some values before continuing, this would only be a partial solution.

Upvotes: 0

Views: 41

Answers (2)

chepner
chepner

Reputation: 532268

Use read.

{
    read a
    read b
    read c
} <<< "$RESULTS"

or use the more standard here document instead of a here string.

{
    read a
    read b
    read c
} <<EOF
$RESULTS
EOF

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 208003

Do you mean this?

a=$(echo -e $RESULTS | awk 'NR==1')
b=$(echo -e $RESULTS | awk 'NR==2')
c=$(echo -e $RESULTS | awk 'NR==3')

echo $a,$b,$c
aaa,bbb,ccc

Upvotes: 0

Related Questions