1

I've got some work to do in bash. It goes like this:

As first argument you type words to find it in the files in the order that it is written, in the second argument you type the directory. It has to search recursively and return the file name where it appears.

For example: bash mybash "alice cat" . it should return files that contains for example: "alice has a cat", "alice cat", but not "cat has alice"

I did smething like this

#!/bin/bash
pattern=".*"

for arg in $1; do
    pattern+="${arg}.*"
done

grep -r ${pattern} $2

but it searches only line by line and doesn't find files with:

"alice something else"

"new line has a cat"

but it should return it.

Some help would be appreciated.

Greets.

jedwards
  • 29,432
  • 3
  • 65
  • 92
tobi
  • 1,944
  • 6
  • 29
  • 48
  • I'm not clear on why it should return "alice something else" but not "cat has alice"? Why should it return "alice something else" when "cat" is not there? – jedwards Apr 30 '12 at 19:41
  • if you type in argument "alice cat" it must be in the file in the same order, so it can't return "cat has alice" because "alice" is before "cat" – tobi Apr 30 '12 at 19:43
  • I understand but the file containing "alice something else" doesn't contain "cat" at all. – jedwards Apr 30 '12 at 19:44
  • and when I typed "alice somethind else" it was a first line of the file and the second line was the "new line has a cat" – tobi Apr 30 '12 at 19:44
  • 1
    Ah, then yes, see the related SO question regarding multiline regex using grep from @frankc. In short, you can't (using grep). – jedwards Apr 30 '12 at 19:45

2 Answers2

1

Does

awk '/alice/,/cat/' file

do what you want?

Jens
  • 69,818
  • 15
  • 125
  • 179
0

If you remove the newlines in your files, then grep will work as you expect.

find $2 -type f | while read file; do
  if tr '\n' ' ' < ${file} | grep -q -r ${pattern}; then
    echo ${file}
  fi
done
leedm777
  • 23,444
  • 10
  • 58
  • 87