Monday, January 31, 2022

[SOLVED] Find a particular string from files under specific directory in LINUX

Issue

I'm trying to fetch particular files which contains string from specific directory.

Say I wanna search for keyword "AAA" from directories with extension "*.BP", what is the equivalent script for the same.

I tried this:

find $T24_HOME -type d -name '*.BP' | xargs -I % grep -l 'searchPattern' %

but it doesn't display the files.


Solution

The output of the find command is a list of directories. You can't run grep -l on a directory, grep wants files to search (unless you specify -r in which case it will check all the files in the directory and all subdirectories recursively).

Also, find has -exec so there's no need to run xargs.

find "$T24_HOME" -type d -name '*.BP' -exec grep -rl 'searchPattern' {} \;

Using + instead of \; (if supported) will run faster as grep won't be invoked for each directory, but will process many directories in one run.



Answered By - choroba
Answer Checked By - Clifford M. (WPSolving Volunteer)