How do I get a key from file matching a pattern in bash, split by =, but where value also can contain = -


i'm reading file , want

  1. get text value key = "key".

    i.e. key = value

  2. trim white space around value or key

however, value can contain = because it's base64 encoded field.

i've been using previously:

key=`egrep 'key' myfile | cut -f2 -d'=' | sed 's/ //g'` 

but, cut works globally. there way of making work on first item?

or perhaps there more efficient way of doing this.

e.g. if myfile = ceph.client.keyring

[client.admin]     key = aqaa6hrvadkxlxaanulnamd/5x2sbly7kppatg==     auid = 0     caps mds = "allow"     caps mon = "allow *"     caps osd = "allow *" 

i'm wanting read variable value key (aqaa6hrvadkxlxaanulnamd/5x2sbly7kppatg==)

using sed

your example myfile:

$ sed -rn '/^[[:space:]]*key[ =]/ s/[^=]*=[[:space:]]*//p' myfile aqaa6hrvadkxlxaanulnamd/5x2sbly7kppatg== 

how works:

  • sed -rn

    this tells sed use extended regular expressions, -r, , not print unless explicitly ask to, -n.

  • /^[[:space:]]*key[ =]/

    this selects lines optionally start whitespace, followed key, followed either blank or equal sign, =.

  • s/[^=]*=[[:space:]]*//p

    for selected lines, strips out before first equal sign , whitespace after equal sign. p option tells sed print resulting line.

using awk

this assumes that, in example, first equal sign surrounded spaces and value key contains no whitespace:

$ awk '$1=="key"{print $3}' myfile aqaa6hrvadkxlxaanulnamd/5x2sbly7kppatg== 

how works:

  • $1=="key"

    this selects lines first field key.

  • {print $3}

    for selected lines, prints third field.

alternate sed solution

doing selecting , substituting in 1 step:

$ sed -rn 's/^[[:space:]]*key[[:space:]]=[[:space:]]*//p' myfile aqaa6hrvadkxlxaanulnamd/5x2sbly7kppatg== 

Comments