M
M
Misty Hedgehog2015-02-06 14:32:28
linux
Misty Hedgehog, 2015-02-06 14:32:28

[SOLVED] Sed, or how to get value from INI file?

Good day.
The task is trifling, but something I was worn out. Bash script, parsing INI file. We get the contents of the section:

## 1. Get section content (text between '[%section_name%]' and next '[')
## 2. Remove lines, what begins on '['..
## 3. Remove empty lines
sectionContent=$(sed -n '/^\['$SectionName'\]/,/^\[/p' $mainVerFile | sed -e '/^\[/d' | sed -e '/^$/d');

As a result, we work with an example:
param1=value1
param2=value2
param3=value3

Now you just need to get the value of " param2 " (the result should be " value2 " without extra characters), but:
  1. Using only sed when possible , as he is the fastest of all ( or is there another, better option? );
  2. We have different line termination characters in different situations (\r || \n || \r\n || \n\r);
  3. It is desirable - in one line, without excessive crutch transformations.

Solution :
## Parse data from passed content of ini section
function getValueFromINI() {
  local sourceData=$1; local paramName=$2;
  ## 1. Get value "platform=%OUR_VALUE%"
  ## 2. Remove illegal characters
  echo $(echo "$sourceData" | sed -n '/^'$paramName'=\(.*\)$/s//\1/p' | tr -d "\r" | tr -d "\n");
}

sectionContent=$(sed -n '/^\[GENERAL_SECTION\]/,/^\[/p' $pathToIniFile | sed -e '/^\[/d' | sed -e '/^$/d');
param1=$(getValueFromINI "$sectionContent" "param1");
param2=$(getValueFromINI "$sectionContent" "param2");
param3=$(getValueFromINI "$sectionContent" "param3");

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Igor, 2015-02-06
@paramtamtam

You just need to find the line containing param2 from three lines and take the value?
If yes, then try this:
awk -F '=' '/param2/ {print $2}'

A
Armenian Radio, 2015-02-06
@gbg

Something like this:

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

Original answer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question