2

I am trying to come up with a function that searches a given file for a given pattern. If the pattern is not found it shall be appended to the file.

This works fine for some cases, but when my pattern includes special characters, like wildcards (*) this method fails.

Patterns that work:
pattern="some normal string"

Patterns that don't work:
pattern='#include "/path/to/dir/\*.conf"'

This is my function:

check_pattern() {
    if ! grep -q "$1" $2
    then
        echo $1 >> $2
    fi
}

I' calling my function like this:
check_pattern $pattern $target_file

When escaping the wildcard in my pattern variable to get grep running correctly echo interprets the \ as character.

So when I run my script a second time my grep does not find the pattern and appends it again.

To put it simple: Stuff that gets appended:
#include "/path/to/dir/\*.conf"

Stuff that i want to have appended:
#include "/path/to/dir/*.conf"

Is there some way to get my expected result without storing my echo-pattern in a second variable?

S.Mathes
  • 21
  • 3
  • Please edit your question to show us how you use your function `check_pattern`. – oliv Sep 24 '19 at 12:25
  • added the part above, calling the function like this: `check_pattern $pattern $target_file` – S.Mathes Sep 24 '19 at 13:13
  • There are a few options on grep that might do much of what you want already: `-F` fixed strings will ignore any regex symbols `-c` count - says how many matches were found - you are interested in an answer of 0 `-m` max num matches per file - same idea, buit aborts early `-H` print filename even if there is only 1 file. – Gem Taylor Sep 24 '19 at 16:15
  • 1
    try `echo "$1" >> $2` . Good luck. – shellter Sep 24 '19 at 16:37
  • and it's worth double-quoting `$2` everywhere as well – jhnc Sep 24 '19 at 19:09

2 Answers2

1

Use

grep -f

and

check_pattern "$pattern" "$target_file"
tripleee
  • 175,061
  • 34
  • 275
  • 318
Flo
  • 11
  • 2
0

Thanks all, I got it now.

Using grep -F as pointed out by Gem Taylor in combination with calling my function like this check_pattern "$pattern" "$target_file" did the tricks.

S.Mathes
  • 21
  • 3