2

I am trying to figure out how to use grep with the patterns in fileA.txt and look for them in fileB.tab. The outcome I want is the number of occurrences of each pattern in fileB.tab.

I have tried:

grep -f FileA.txt FileB.tab | wc -l

But I think that is giving me back all the lines in FileB.tab where a fileA.tab pattern appears.

  • I don't think there's a way to do with grep alone.. you'll have to iterate over each line of FileA.txt in a loop – Sundeep Apr 6 '17 at 12:07
1

If the patterns file contains only fixed strings, on a gnu setup you could do

grep -oFf patterns infile | sort | uniq -c

If the content is regex then maybe something like

sed -E 'h;s|/|\\&|g;x;s|[\&/]|\\&|g;H;x;s|(.*)\n(.*)|s/\1/\2/|' patterns \
| sed -f - <(grep -of patterns infile)  | sort | uniq -c

that is use the same grep command only this time process the result with sed so as to replace the matches with the actual pattern (via another sed script based on the content of patterns)

0

uniq has an option to count the occurences

grep -f fileA.txt fileB.txt | uniq -c

Keep in mind though, if you have duplicates in your fileA, the count won't be correct, since it will grep for them several times. In this case run fileA through uniq first to remove duplicates, then use it for the patterns.

You could filter it into a new file, or process the file line by line and run from that.

while read keyword; do grep $keyword fileB.txt; done < fileA.txt | uniq -c

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.