I am new to shell scripting, and I have a need which I am explaining by using a sample example. I have a property file which will contain data as shown below :
object1 : propertyA
object2 : property1 property2
object3 : propertyxyz
Note : On the whole I have some objects which can have any number of properties. And I need to keep this in a property files so that it can be changed as per need.
All I need is if I get object 3 as a user input then my code should print all the respective properties.
I have tried using .ini files, but I dont want to use any external parsers. And which ever comes with bash seems to not helping me in this case. if I use grep then I would have to split the properties using some regex.
.ini file which I created :
[object1]
property=propertyA
[object2]
property=property1
property=property2
[object3]
property=propertyxya
I am looking for a solution in which if I select an object ( which in case of ini files it is a section) then I should get all the properties in an array.
So is there any thing which is predefined in bash or do I need to write using grep n regex only.
It can be done pretty easily using
Awk
, just do the below to store the contents in abash
array.Now loop the array to print the properties,
(or) just
The
Awk
command works as follows:-Awk
using the-v
syntax and doing a regex match$1 ~ input
to match the line containing user input, sayobject1
$1 ~ /\[object/{flag=0; next}
flag && NF
takes care of processing only non-empty lines and only property values after the requested object.split()
function inAwk
, we can extract the value of property and print it, which will be later stored in the array.Put the line with
read
and the line below as shown in abash
script with she-bang set to#!/bin/bash
and run it.E.g. in a complete script as
A few sample runs on the script.
There is a project which provides a function to parse ini files: bash_ini_parser
It requires bash only, no other tools needed.
I would do something like this, where
XXXXXXX
is the object name :For example :
See this post for more info : How to select lines between two patterns?.
For the formatting in an array, it will depend what the array should look like
With
awk
we can have a regex for the [object] line and we just capture it. Then we have a regex for theproperty=
line and, here, we join the object to the property:Which produces the intermediate output:
Then, to get the properties, of, say, [object2], we simply use
grep
andsed
:This produces: