4

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

2

4 Answers 4

10

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.
Sign up to request clarification or add additional context in comments.

3 Comments

/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 *.*
how to make it not display the substring in result output? eg only output = filenames, nothing else
@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.
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

Comments

2

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

Comments

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

3 Comments

You want to list the files from directory?
i want to list the files from the directory which contains specific string for example : if a file contain 57690 it should be listed
alright use the first command I mentioned in my question, that will do the job.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.