Igor
Igor

Reputation: 1211

Check which INI file section has a specific key

I have an ini file, which can only have two states. State one:

[General]
StartWithLastProfile=0

[Profile0]
Name=default
IsRelative=1
Path=Profiles/kn081mln.default
Default=1

[Profile1]
Name=Dark
IsRelative=1
Path=Profiles/elqlrk57.Dark

State two:

[General]
StartWithLastProfile=0

[Profile0]
Name=default
IsRelative=1
Path=Profiles/kn081mln.default

[Profile1]
Name=Dark
IsRelative=1
Path=Profiles/elqlrk57.Dark
Default=1

The difference between the two is whether section Profile0 or Profile1 has the key Default=1. How can I check under which of these two sections Default=1 is using bash?

Upvotes: 1

Views: 260

Answers (2)

Igor
Igor

Reputation: 1211

After some tinkering, figured out this could be done with some Python inside bash script:

#!/bin/bash
foo=$(python - << EOF
import configparser
config = configparser.ConfigParser()
config.read('/path/to/file.ini')

if config.has_option('Profile0', 'Default'):
    print('Default is Profile0')
else:
    print('Default is Profile1')
EOF)

echo $foo

Upvotes: 1

dibery
dibery

Reputation: 3460

You may use

awk '/\[Profile[01]\]/ {label=$0} /Default/ {print label}'

Explanation:

If a line matches the categorical label, remember the current category.

The category pattern I use here is \[Profile[01]\]. Since [] is treated as a set when not escaped, the literal [] must be escaped, and the [01] is used as the character set.

If the desired key appears, output the label.

Upvotes: 2

Related Questions