Oct 9, 2012

Scripting in Bash: Convert string to array

It is a simple example how to convert multi-line string into array.


Script source:
#!/bin/bash

STRING='First line
Second line
Third line'

let I=0

while read LINE
do
    LINES[$I]=$LINE
    (( I++ ))
done <<< "$STRING"

echo "Number of lines ${#LINES[@]}"
echo "LINES[0]='${LINES[0]}'"
echo "LINES[1]='${LINES[1]}'"
echo "LINES[2]='${LINES[2]}'"


Execution log:
[cloudera@localhost scripts]$ chmod +x string2array.sh 
[cloudera@localhost scripts]$ ./string2array.sh 
Number of lines 3
LINES[0]='First line'
LINES[1]='Second line'
LINES[2]='Third line' <<<

No comments: