简体   繁体   中英

Searching within txt files using bash

I am looking trivial solution for the trivial task.

My bash script is looping several folders producing in which some log.txt file. If some operation in each case has performed successfully in each of the log the string with sentence "The unit is OK" should somewhere in the log.txt appeared, however its actual position (precise number of string) in each log.txt is differs!

I need to put in my loop some condition (probably using IF ) to check whether that sentence is actually present somewhere in the log file and if so - to print "Everything is OK" within the terminal where my script is executed in moment of looping of particular folder, and otherwise (if the string is absent in the log) to print smth like "Bad news"!

Will be thankful for the different solutions especially how to find the strings of selected phrases in the given log file.

Thanks!!

Gleb

To apply the test to an entire directory, a simple for loop can be use. If you need to process directories recursively, you can feed a while read -r... loop with the results of find . In either case the search with be similar. Here is an example searching a single directory of log files:

$ for i in dirname/*; do grep -q 'The unit is OK' "$i" && \
echo "$i - Everything is OK" || echo "$i - Bad news"; done

Searching where dirname is my test dat directory, example results would be:

dat/test.properties - Bad news
dat/test_pph_s.txt - Bad news
dat/testlog-1.txt - Everything is OK
dat/testlog-2.txt - Everything is OK
dat/testlog-3.txt - Everything is OK

Where the testlog-X.txt files contain, for example:

$ cat dat/testlog-1.txt
The unit is OK

Without more info (examples of strings you are looking for, potential file names, whatever bash script you already have) it is hard to provide concrete advice.

Still, if you have a known set of potential strings you could check for their existence in a file while you're looping

if [ `grep -E (pattern1|pattern2|pattern3) $FILE | wc -l` -gt 0 ]; then
    # String was found in file
fi

Scanning files with some pattern (eg: log.txt)

for file in $(find /path/to/logs -name "log.txt")
do
  grep -q "The unit is OK" $file && echo "$file: Everything is OK" || echo "$file: Bad news"
done

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