2

I need to list files from a directory which contains a specific string using linux commands.

Deepi
  • 41
  • 1
  • 1
  • 2
  • 4
    contain 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 Answers4

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, and
  • r to recursively read all files under each directory.
Lucas
  • 523
  • 2
  • 10
  • 20
skr
  • 2,146
  • 19
  • 22
  • `/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
  • 1
    how to make it `not` display the substring in result output? eg only output = filenames, nothing else – parsecer Jan 20 '22 at 01:42
4

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

xiawi
  • 1,772
  • 4
  • 19
  • 21
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