1

I have a directory PAYMENT. Inside it I have some text files.

xyx.txt
agfh.txt
hjul.txt

I need to go through all these files and find how many entries in each file contain text like BPR.

If it's one I need to get an alert. For example, if xyx.txt contains only one BPR entry, I need to get an alert.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Nevin Thomas
  • 806
  • 4
  • 12
  • 24
  • possible duplicate of [count all occurrences of string in lots of files with grep](http://stackoverflow.com/questions/371115/count-all-occurrences-of-string-in-lots-of-files-with-grep) – tripleee Oct 07 '13 at 15:39

3 Answers3

6

You do not need to loop, something like this should make it:

grep -l "BPR" /your/path/PAYMENT/*
  • grep is a tool to find lines matching a pattern in files.
  • -l shows which files have that string.
  • "BPR" is the string you are looking for.
  • /your/path/PAYMENT/* means that it will grep throughout all files in that dir.

In case you want to want to find within specific kind of files / inside directories, say so because the command would vary a little.


Update

Based on your new requests:

I need to go through all these files an find how many entries in each file like BPR.

If its one I need to get an alert. For example, if xyx.txt contains only one BPR entry, I need to get an alert.

grep -c is your friend (more or less). So what you can do is:

if [ "$(grep -c a_certain_file)" -eq 1 ]; then
    echo "mai dei mai dei"
fi
Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
1

i need to go through all these files an find is there an entry like 'BPR'

If you are looking for a command to find file names that contain BPR then use:

echo /path/to/PAYMENT/*BPR*.txt

If you are looking for a command to find file names that contain text BPR then use:

grep -l "BPR" /path/to/PAYMENT/*.txt
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Give this a try:

grep -o BPR {path}/* | wc -l

where {path} is the location of all the files. It'll give you JUST the number of occurrences of the string "BPR".

Also, FYI - this has also been talked about here: count all occurrences of string in lots of files with grep

Community
  • 1
  • 1
Greg Gauthier
  • 1,336
  • 1
  • 12
  • 25