简体   繁体   中英

How to loop through all files in a directory and find if a value exists in those files using a shell script

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM