TransWikia.com

How to validate a line if followed by a specifc line?

Unix & Linux Asked by user441539 on December 29, 2020

On some our Linux servers we have the following files:

/etc/ambari-agent/conf/ambari-agent.ini

The files include the following example of lines:

; memory_threshold_soft_mb=400
; memory_threshold_hard_mb=1000
; ignore_mount_points=/mnt/custom1,/mnt/custom2

[security]
force_https_protocol=PROTOCOL_TLSv1_2
keysdir=/var/lib/ambari-agent/keys
server_crt=ca.crt
passphrase_env_var_name=AMBARI_PASSPHRASE

what we want to do is to verify the full match of the line – force_https_protocol=PROTOCOL_TLSv1_2 under [security]

so we did the following ( this line is part of bash script )

[[ `  grep -xA 0 "force_https_protocol=PROTOCOL_TLSv1_2" /etc/ambari-agent/conf/ambari-agent.ini | wc -l ` -eq 1 ]] && echo "full match"

this works but we not sure if our approach is the right full match

I will happy to get other ideas

The target is to verify if the line force_https_protocol=PROTOCOL_TLSv1_2 appears after the line – [security] ( this is must ) , and need to also verify that line is fully matched with force_https_protocol=PROTOCOL_TLSv1_2

2 Answers

You can use grep and enabling PCRE in this way:

<infile grep -zqP '[security]nforce_https_protocol=PROTOCOL_TLSv1_2n' 
    && echo "found" || echo "not found"

in case that if that line was not immediately after [security], just change

[security]n with [security]n.*n in the command.


to making sure it only appear once, you can add -c option for the grep and verify it.

[[ $(grep -zcP '[security]nforce_https_protocol=PROTOCOL_TLSv1_2n' infile) -eq 1 ]] && echo found

or equivalently:

(($(grep -zcP '[security]nforce_https_protocol=PROTOCOL_TLSv1_2n' infile) == 1)) && echo found

Correct answer by αғsнιη on December 29, 2020

You can parse that INI file with gnu awk:

gawk '
    match($0, /^[(.+)]$/, m) {is_security = m[1] == "security"}
    is_security && $0 == "force_https_protocol=PROTOCOL_TLSv1_2" {valid=1; exit}
    END {
        if (valid) {print "valid"} else {print "not valid"}
        exit (!valid)
    }
' file.ini

Answered by glenn jackman on December 29, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP