Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

95
Views
How to find whether any file of a directory contains a specific string using bash script?

I need to check if the string M1039C28 is inside any file of the directory /var/opt.
It should echo true if the string is found or echo String not found if the string is not found.

Sample:

cd /var/opt/;
if [ find ./ -type f -exec grep -Hni "M1039C28" {} ';']
then
    echo "String found"
else
    INFO "String not found"
fi
9 months ago · Santiago Trujillo
3 answers
Answer question

0

Consider using grep with options -q (suppress any output) and -r (recursive search in a directory):

grep -qr "search-query" /path/to/dir && echo "FOUND" || echo "NOT FOUND"

grep will exit with code 1 if it could not find the string in any files. For more information, see the man page

9 months ago · Santiago Trujillo Report

0

Why don't you base your script on this command:

grep -l "M1039C28" * | wc -l

If the result is 0, then the entry is not found.
If the result is 1 or more, the entry is found.

9 months ago · Santiago Trujillo Report

0

If you have a large directory and want to search recursively, try using the silver searcher if not already installed, you can with on Debian sudo apt install silversearcher-ag or brew install the_silver_searcher on MacOS. Use it like this.

ag "M1039C28" path/to/search && echo "FOUND" || echo "NOT FOUND"

note path argument is optional, by default it searches current path recursively.

9 months ago · Santiago Trujillo Report
Answer question
Find remote jobs