Issue
I have a file that has such a structure:
section "first_section" {
parameter1 = value1
parameter2 = value2
parameter3 = value3
}
section "second_section" {
parameter1 = value1
parameter2 = value2
parameter3 = value3
}
...
And I have a variable that contains a new section, for example:
section "third_section" {
parameter1 = value1
parameter2 = value2
parameter3 = value3
}
I'd like to check in Bash before adding a new section if that section already exists in the file.
I was trying something like
if grep -q -z "$section" file.txt
then
echo "Duplicate found"
else
echo "$section" >> ./file.txt
fi
However, I always get a Duplicate found
output even if it is not true.
Solution
I'd use bash builtin pattern matching with the [[...]]
construct:
When the ‘==’ and ‘!=’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described in Pattern Matching
contents=$(< filename)
section='section "third" {...}'
if [[ $contents == *"$section"* ]]; then
echo "file already contains the section"
else
# append it to the file
echo "$section" >> filename
end
Answered By - glenn jackman Answer Checked By - Marilyn (WPSolving Volunteer)