简体   繁体   中英

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"

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 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, eg:

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

使用find

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

如果模式必须是正则表达式:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM