I need to list files from a directory which contains a specific string using linux commands.
Asked
Active
Viewed 2.7k times
2
-
4contain in the filename or inside? text files? – Mithun Sasidharan Jun 13 '17 at 11:56
-
Possible duplicate of [How do I find all files containing specific text on Linux?](https://stackoverflow.com/questions/16956810/how-do-i-find-all-files-containing-specific-text-on-linux) – xiawi Jun 13 '17 at 12:03
4 Answers
9
Use the command
grep -inr <string> /path/to/directory
The -inr
option has three parts:
i
to ignore case sensitivity,n
to display the line numbers in for each matched result, andr
to recursively read all files under each directory.
-
`/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 `*.*` – aiman Dec 23 '20 at 08:29
-
1how to make it `not` display the substring in result output? eg only output = filenames, nothing else – parsecer Jan 20 '22 at 01:42
1
You could do
grep -nr <string> <path to the directory>
This will print the name of the files with the line number containing the string
If you want to list file name(s) with a particular string then do
find <path to the directory> -iname <string_pattern> -type f

Mayur Nagekar
- 813
- 5
- 13
0
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

danglingpointer
- 4,708
- 3
- 24
- 42
-
-
i want to list the files from the directory which contains specific string for example : if a file contain 57690 it should be listed – Deepi Jun 13 '17 at 12:41
-
alright use the first command I mentioned in my question, that will do the job. – danglingpointer Jun 13 '17 at 12:43