54l3d
54l3d

Reputation: 3973

Get files which contains a specific text using Linux

I want to find files in Linux, in a specific directory without looking into its subdirectories, which contains in their text a specific string. From this answer, I tried this after removing the r of recursion:

grep -nw '/path/to/somewhere/' -e "pattern"

But it not working. I tried also this with skipping directory optin:

grep -rnw -d skip '/path/to/somewhere/' -e "pattern"

I tried to exclude any directory that is different from the current directory, but also no way:

grep -rnw -exclude-dir '[^.]' '../../path/to/somewhere/' -e "pattern"

Upvotes: 0

Views: 1814

Answers (3)

Ruslan Osmanov
Ruslan Osmanov

Reputation: 21492

May be the question was confusing, i hope its clear now, the patten should match the content not the filename !

Your question was not clear, and in the original answer I have shown how to find filenames matching a pattern. If you only want to search for files with content matching a pattern, it's as simple as

grep 'pattern' directory/*

(the shell globbing is used).

You can still use find to filter out the files before passing to grep:

find 'directory' -maxdepth 1 -mindepth 1 -type f \
  -exec grep --with-filename 'pattern' {} +

Original Answer

Grep is not appropriate tool for searching for filenames, since you need to generate a list of files before passing to Grep. Even if you get the desired results with a command like ls | grep pattern, you will have to append another pipe in order to process the files (I guess, you will most likely need to process them somehow, sooner or later).

Use find instead, as it has its own powerful pattern matching features.

Example:

find 'directory' -maxdepth 1 -mindepth 1 -regex '.*pattern'

Use -iregex for case insensitive version of -regex. Also read about -name, -iname, -path, and -ipath options.


It is possible to run a command (or script) for the files being processed with -exec action, e.g.:

find 'directory' -maxdepth 1 -mindepth 1 -type f \
  -regex '.*pattern' -exec sed -i.bak -r 's/\btwo\b/2/g' {} +

Upvotes: 2

user1934428
user1934428

Reputation: 22225

If the pattern must be a regular expression:

ls -A /path/to/dir | grep -E PATTERN

Upvotes: 0

Phylogenesis
Phylogenesis

Reputation: 7880

Using find:

find '/path/to/somewhere' -maxdepth 1 -type f -exec grep -H 'pattern' {} \;

Upvotes: 1

Related Questions