Heuristic
Heuristic

Reputation: 5341

Shell script reading/formatting config file

I've searched a few places and didn't find one for my needs, basically here's the config:

name1 = value1;
name2= value2
name3 =value3 // comments

name4=value4 //empty line above and/or below

I need a shell script that reads the config file and parse all the name / value pairs with starting/trailing semicolons/spaces removed and comments as well as empty lines ignored.

I first tried

while read -r name value
do
echo "Content of $name is ${value//\"/}"
done < $1

I tried to trim name and value by:

"${var//+([[:space:]])/}"

but still not sure how to remove the semicolon and ignore the empty lines and comments?

Upvotes: 1

Views: 231

Answers (1)

yacc
yacc

Reputation: 3361

This is where IFS could be used. You'll have to rely on sed, however, and assume a well-formed config file. No multiline values like that.

parseconf() {
  sed -e 's/^[ ;]*//' \
      -e 's/[ ;]*$//' \
      -e 's/\/\/.*//' \
      -e 's/ *= */=/' $1 \
  | while IFS="=" read -r name value
  do
    [ -n "$name" ] && echo "name=$name value=$value"
  done
}
parseconf $1

Upvotes: 1

Related Questions