bashini

Parsing .ini file in bash


I have a below properties file and would like to parse it as mentioned below. Please help in doing this.

.ini file which I created :

[Machine1]

app=version1


[Machine2]

app=version1

app=version2

[Machine3]

app=version1
app=version3

I am looking for a solution in which ini file should be parsed like

[Machine1]app = version1
[Machine2]app = version1
[Machine2]app = version2
[Machine3]app = version1
[Machine3]app = version3

Thanks.


Solution

  • Try:

    $ awk '/\[/{prefix=$0; next} $1{print prefix $0}' file.ini
    [Machine1]app=version1
    [Machine2]app=version1
    [Machine2]app=version2
    [Machine3]app=version1
    [Machine3]app=version3
    

    How it works

    Adding spaces

    To add spaces around any occurrence of =:

    $ awk -F= '/\[/{prefix=$0; next} $1{$1=$1; print prefix $0}' OFS=' = ' file.ini
    [Machine1]app = version1
    [Machine2]app = version1
    [Machine2]app = version2
    [Machine3]app = version1
    [Machine3]app = version3
    

    This works by using = as the field separator on input and = as the field separator on output.