How to find a string in files in linux Ubuntu
The commands used are mainly grep and find.
Find string in file
grep string filename
grep name file.txt
Find string in file ignoring cases
grep string filename
grep -i name file.txt
Find string in current directory
grep string .
grep name .
Find string recursively
grep -r string .
grep -r name .
Find files that do not contain a string
grep -L string .
grep -L "foo" *
Find string recursively in only some specific files
grep string -r . --include=*.myextension
grep string -r . --include=*.{myextension,myextension2}
grep "name=Oscar" -r . --include=*.js
* if you specify --include it won't look for the string in all files, just the ones included
Find string recursively in all files except the ones that contain certain extensions
grep string -r . --exclude=*.{myextension2}
grep "Serializable" -rl . --exclude=*.{jar,class,svn-base,index}
Find string recursively all files including some extensions and excluding others
grep string -r . --include=*.myextension --exclude=*.myextension2
grep string -r . --include=*.{myextension,myextension2} --exclude=*.{myextension3,myextension2}
grep "my=string" -r . --include=*.{js,html} --exclude=*.js
*It won't look for the string in the js files.
Find string recursively in only some specific files and show their filename
grep string -rl . --include=*.myextension
grep "name=Oscar" -rl . --include=*.js
Find files and find a string in them using find
find . -name '*.extension' -exec grep string +
find . -name '*.txt' -exec grep Mytext {} +
find . -type f \( -name '*.htm' -or -name '*.html' \) -exec grep -i "mystring" {} +
Notes
- Use double quotes "String" if the string contains spaces
- Mind the empty spaces between extensions between the curly braces e.g.{txt, html}
- Don't use curly braces for one extension e.g{html}