Reputation: 173
My code read a file by line and split each line by a comma ; or space and the results is affected to an array, but the proble is that i can't read the elmen of the array
#!/bin/bash
filename="$1"
while read -r line
do
name=$line
echo "Name read from file - $name"
arr=$(echo $name | tr ";" "\n")
echo ${arr[1]}
for x in $arr
do
echo "> [$x]"
var1=$x
var2=$x
done
done < "$filename"
the problem is in the command:
echo ${arr[1]}
the file that i use contain line :
car; vehicle
computer;apple
Upvotes: 0
Views: 63
Reputation: 785376
To loop through an array:
for x in "${arr[@]}"; do
echo "> [$x]"
done
The ${arr[@]}
expansion will include the entire array, while $arr
alone only includes the first array element.
However if you use read -ra
with custom IFS
then you can directly read each delimited line into an array:
while IFS=';' read -ra arr; do
printf "[%s]\n" "${arr[@]}"
echo '----------'
done < file
Output:
[car]
[vehicle]
----------
[computer]
[apple]
----------
Upvotes: 2