Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing .ini file in bash

Tags:

bash

ini

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.

like image 517
Ras Avatar asked Mar 21 '18 06:03

Ras


1 Answers

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

  • /\[/{prefix=$0; next}

    If any line begins with [, we save the line in the variable prefix and then we skip the rest of the commands and jump to the next line.

  • $1{print prefix $0}

    If the current line is not empty, we print the prefix followed by the current line.

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.

like image 171
John1024 Avatar answered Sep 28 '22 08:09

John1024