I need to list files from a directory which contains a specific string using linux commands.
-
4contain in the filename or inside? text files?Mithun Sasidharan– Mithun Sasidharan2017-06-13 11:56:00 +00:00Commented Jun 13, 2017 at 11:56
-
Possible duplicate of How do I find all files containing specific text on Linux?xiawi– xiawi2017-06-13 12:03:10 +00:00Commented Jun 13, 2017 at 12:03
Add a comment
|
4 Answers
Use the command
grep -inr <string> /path/to/directory
The -inr option has three parts:
ito ignore case sensitivity,nto display the line numbers in for each matched result, andrto recursively read all files under each directory.
3 Comments
aiman
/path/to/directory would actually be path to the file if you are looking in this directory itself with no recursion required. remove -r also. If name of the file is not know then *.*parsecer
how to make it
not display the substring in result output? eg only output = filenames, nothing elseJacques
@parsecer You can use the lower L tag
grep -l (files-with-matches) for that. This also skips the rest of the file on the first match so that could be a performance improvement.Let say your string is in the environment variable STR and you search in directory dir/. You can do:
find dir/ -type f -name "*${STR}*"
If you search a file containing the string:
find dir/ -type f -exec grep -l $STR {} \;
But this is explained here
Comments
This command will find files with matching string. However, I added little more extra, exec will list the files.
command
find <your/dir/> -name "string_to_search*" -type f -exec ls -l {} \;
or this command will list all the c files in your directory.
find <your/dir/> -name "*.c" -type f -exec ls -l {} \;
Using find command to find the matching string inside the file.
find -type f | xargs grep 'text-to-find-here'
Here / means search in all dirs
find / -type f | xargs grep 'text-to-find-here'
or
grep -r "string to be searched" /path/to/dir
3 Comments
danglingpointer
You want to list the files from directory?
Deepi
i want to list the files from the directory which contains specific string for example : if a file contain 57690 it should be listed
danglingpointer
alright use the first command I mentioned in my question, that will do the job.