I read a text file line by line in a bash script, the goal is to catch variable declarations.
The bash script:
#!/bin/bash
filePath=$1
while read line
do
if [[ $line =~ ^[[:blank:]]*([^#[:blank:]]+)[[:blank:]]*=[[:blank:]]*(.*) ]]
then
var=${BASH_REMATCH[1]}
value=${BASH_REMATCH[2]}
echo "$var=$value"
fi
done < "$filePath"
With this text file (note that the line "c=3" is the last line of the file):
# First variable
a=1
# Second variable
b = 2
# Third variable
c=3
The output is:
a=1
b=2
But with this one:
# First variable
a=1
# Second variable
b = 2
# Third variable
c=3
# empty line
The output is:
a=1
b=2
c=3
It can be an empty line at the end, not necessary a comment.
Can someone explain why the last line is not catched by the regex in the first example? And how can I fix the problem (except from adding an empty line at the end of the text file...)? Thanks