Home > Net >  How to find multiline text in file using bash
How to find multiline text in file using bash

Time:11-26

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.

CodePudding user response:

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

CodePudding user response:

Based on this post https://unix.stackexchange.com/questions/528146/how-to-grep-multi-lines , if your GNU grep supports the P flag you could do something like:


section='section "third_section" {
  parameter1 = value1
  parameter2 = value2
  parameter3 = value3
}'

if grep -qozP  'section "third_section" {(\n.*){1,}}' file.txt; then
  printf 'Duplicate\n' >&2
else
  printf '\n%s' "$section" >> file.txt
fi

  • Assuming third_section does not have a duplicate entry with a different entry/contents/values.

  • Remove the -q flag to see the output of grep

  •  Tags:  
  • bash
  • Related