0

Trying to grep with patterns from one file and use them on a big one file and then save results to files with pattern name and grep output inside, does not work, empty files created.

What I am doing wrong?

while read p; do
grep $p big.txt >>$p
done < patterns.txt 
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • What's the `patterns.txt` file like? In case it contains names with spaces, you can have problems. – fedorqui Jan 06 '14 at 12:47
  • the `-f` option read patterns from a file: `grep -f patterns.txt big.txt >>output` but if you need a different file foreach pattern, then you gave yourself already a solution, except that you have to be careful with what the read pattern contains (slashes, spaces, ...). Then, if a pattern gives no match, of course you will have empy files. Try the option `-c` to have a count of matches; if the files contains `0` (matches), then it means your pattern doesn't match any line of the input. – ShinTakezou Jan 06 '14 at 12:47
  • patterns file contains simple word list , second level domain names, no slashes dots spaces and so on, words, words with hyphens. with -f tag empty files too. – user1983793 Jan 06 '14 at 13:00
  • Strange. What if you `grep something big.txt`? Try also to do `grep "$p" big.txt >> "$p"`, that is, to quote variables. – fedorqui Jan 06 '14 at 13:03
  • Thank you! >> "$p" did it :) (quotes) – user1983793 Jan 06 '14 at 13:13

1 Answers1

0

As indicated in comments, you'd better quote the variables so that strange characters in the patterns.txt file will be treated as text:

while IFS= read -r p; do
  grep "$p" big.txt >> "$p"
done < patterns.txt

See Read a file line by line assigning the value to a variable for an explanation on IFS= and read -r.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598