Find a file that contains a string

  • Thread starter Karthik Rajashekaran
  • Start date
K

Karthik Rajashekaran

Guest
Hi

I am trying to find a command to find a string in a file in Linux /Unix

Note : you dont know which directory the file is or which file does it have the string
 


No this case you need to mention the file name ... Here I dont know file name and path .. So it has search the entire directory and file and get the matches
 
( @ryanvade I saw that too.)

@Karthik Rajashekaran If you don't specify a Directory it will take a VERY, VERY long time to come up with an answer because it is searching every file on the Hard Drive. You need to wait forever - and then some more.
 
Also, if you start your grep at "/", you'll have some issues with permissions, unless you are root.

You can save yourself some time and aggravation if you can skip binaries, also.

so: sudo grep -rI "text string to search” /*
 
Also, if you start your grep at "/", you'll have some issues with permissions, unless you are root.

You can save yourself some time and aggravation if you can skip binaries, also.

so: sudo grep -rI "text string to search” /*
Not sure if case matters. But yeah, use sudo or run the command as root.
 
well for a case-insensitive grep, use -i (-I means ignore binary, of course).
 
I prefer to use grep in conjunction with find for this kind of effort. Ie:

find /path -exec grep "Search String Here" {} \; -ls
 
Use this for color coded results back:
Code:
grep -iIHrn --color=always yourtexthere . | less -r

You can also make a function for it in your .bashrc file:
Code:
# Searches for text in all files in the current folder
ftext ()
{
   # -i case-insensitive
   # -I ignore binary files
   # -H causes filename to be printed
   # -r recursive search
   # -n causes line number to be printed
   # optional: -F treat search term as a literal, not a regular expression
   # optional: -l only print filenames and not the matching lines ex. grep -irl "$1" *
   grep -iIHrn --color=always "$1" . | less -r
}
 

Members online


Top