Shell – Find a string (like grep -q) within only a section of a file

awkgrepshelltext processing

I want to write some Bash that can verify that a string exists in a configuration file. I can't change the file format, it belongs to a different application.

The file is subdivided into groups named by strings in square brackets.

This should be a success:

[group1]
MyParameter
junk1
junk2

[group2]
junk3
junk4

This should be an error:

[group1]
junk1
junk2

[group2]
MyParameter
junk3
junk4

I can do a grep -q to verify that MyParameter exists in the file, but if it's located in some other group and not group1, then I'm still busted.

If MyParameter existed in both groups, I wouldn't care enough to flag an error, as long as it existed in group1.

I can't depend on line numbers (head, tail, etc). Also, I'd be happier if it was generic enough that it doesn't depend on the name of group2 (the script would just know that if it found another line beginning and ending with square brackets, that terminates the previous group).

Best Answer

Whenever faced with a text processing problem, some people say “let's use awk”. More often than not, they have a solution.

awk '
    /^\[.*\]$/ {group = $0}
    group == "[group1]" && $1 == "MyParameter" {found=1; exit}
    END {exit !found}
'
Related Question