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
  • 252,262
  • 96
  • 511
  • 570
  • 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
  • Good to read that, @user1983793 I just posted this as an answer. Since you're new here, please don't forget to mark the answer accepted if your problem is already solved. You can do it clicking on the check mark beside the answer to toggle it from hollow to green. See [Help Center > Asking](http://stackoverflow.com/helpcenter/someone-answers) if you have any doubt! – fedorqui Jan 06 '14 at 13:16

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
  • 252,262
  • 96
  • 511
  • 570