How to find all files containing specific text on Linux?

In linux, to find all files containing a specific text, we can use the grep command, which can search for the specified text in the file.

In the following example, we will introduce two methods to find all files containing the specified text.

use grep command

Syntax

grep -rnw '/path/to/somewhere/' -e 'pattern'
  • -r or -R is recursive,
  • -n is line number, and
  • -w stands for match the whole word.
  • -l (lower-case L) can be added to just give the file name of matching files.
  • -e is the pattern used during the search

Example

➜  ~ grep -rnwl ~/Documents/blog -e "linuxcommand"
/Users/ylspirit/Documents/blog/awk/grep/test1.txt
/Users/ylspirit/Documents/blog/grep/test1.txt
➜  ~
➜  ~ grep -rnw ~/Documents/blog -e "linuxcommand"
/Users/ylspirit/Documents/blog/awk/grep/test1.txt:8:linuxcommand
/Users/ylspirit/Documents/blog/grep/test1.txt:8:linuxcommand

use grep command and find command

Syntax

find '/path/to/somewhere/' -type f | xargs grep -hl 'pattern'
  • find -type f is find files only.

Example

➜  ~ find ~/Documents/blog -type f | xargs grep -hl 'linuxcommand'

All right.

Add a Comment

Your email address will not be published.