DEV Community 👩‍💻👨‍💻

abbazs
abbazs

Posted on

How to find lines containing a specific text in linux?

Using grep we can do this.

grep -rnw '/path/to/somewhere/' -e 'pattern'
Enter fullscreen mode Exit fullscreen mode

-r or -R is recursive
-n is line number
-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
--exclude, --include, --exclude-dir flags can be used for targeted search

To search python or in json files only

grep --include=\*.{py,json} -rnw '/path/to/somewhere/' -e "pattern"
Enter fullscreen mode Exit fullscreen mode

To search excluding pyc files

grep --exclude=\*.pyc -rnw '/path/to/somewhere/' -e "pattern"
Enter fullscreen mode Exit fullscreen mode

To search excluding directories

grep --exclude-dir={test,.vscode, *__cache*} -rnw '/path/to/somewhere/' -e "pattern"
Enter fullscreen mode Exit fullscreen mode

To list only the file names containing search text

grep -rl '/path/to/somewhere/' -e "pattern"
Enter fullscreen mode Exit fullscreen mode

For detailed options refer to man pages or man grep

Top comments (0)

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.