1

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?

5
  • You are asking us wriite a complete parser for an incompletely specified file format? In shell script? Seriously? Commented Oct 12, 2015 at 5:36
  • A somewhat more sane approach would be to preprocess the input to remove comments and value-final semicolon terminators, and normalize whitespace. Then the rest is extremely easy. Commented Oct 12, 2015 at 5:37
  • @tripleee Yes I see, the format is just what's in the first quoted part, name value pairs separated by equal sign, with optional spaces and comments. Commented Oct 12, 2015 at 5:47
  • If you are fine with a Bash solution, replace < $1 (which should properly be < "$1") with something like < <(sed -e '/^$/d' -e 's%[[:space:]]*//.*%%' -e 's/;$//' -e 's/[[:space:]]*=[[:space:]]*/ /' "$1") Commented Oct 12, 2015 at 5:52
  • Or why worry about a "parser", just change the comment identifiers to #, remove the spaces on either side of the = sign, and then source config.file into your script... That would make a lot more sense... Commented Oct 12, 2015 at 6:10

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.