We help IT Professionals succeed at work.

parse mongod file and get port and replSetName

Medium Priority
181 Views
Last Modified: 2019-04-01
Hello,

How can I parse mongod file and get port and replSetName ?

net:
  port: 27017
  bindIp: 0.0.0.0

replication:
  replSetName: TESTREPL
  oplogSizeMB: 2048

I try without result :
pw=$(awk '/^ port/{print $3}' mongod.conf)

user=$(awk '/^replSetName/{print $3}' mongod.conf)

Thank you
Comment
Watch Question

Duncan RoeSoftware Developer
CERTIFIED EXPERT

Commented:
Why $3 and not $2? I.e. pw=$(awk '/^ port/{print $2}' mongod.conf)
CERTIFIED EXPERT
Commented:
In addition to Duncan's correction, I would add these:

The number of spaces between the "^" and "port" or "replSetName" should be the same as the number of spaces on the left of these 2 lines:
  port: 27017
  replSetName: TESTREPL
It looks as if there are 2 spaces on the left of those 2 lines, so unless something's been lost in a copy/paste (please check), I suggest you change this:
    pw=$(awk '/^ port/{print $2}' mongod.conf)
to this:
    pw=$(awk '/^  port/{print $2}' mongod.conf)
and this:
    user=$(awk '/^replSetName/{print $3}' mongod.conf)
to this:
    user=$(awk '/^  replSetName/{print $2}' mongod.conf)
Duncan RoeSoftware Developer
CERTIFIED EXPERT
Commented:
To cater for any amount of white space, you can use:

pw=$(awk '/^[[:space:]]*port/{print $2}' mongod.conf)

Author

Commented:
Hello,

Than you, I have tested :
pw=$(awk '/^[[:space:]]*port/{print $2}' mongod.conf)
The result is 27018

I search to return port:27018

Thank you

Best regards
CERTIFIED EXPERT
Commented:
Hi bibi92,

Why did you accept my solution as "the solution"?  Duncan wrote most of the code, I just offered some minor adjustments.