LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Help with BASH to search text files on disk (https://www.linuxquestions.org/questions/linux-newbie-8/help-with-bash-to-search-text-files-on-disk-622146/)

purveshk 02-19-2008 12:18 AM

Help with BASH to search text files on disk
 
Hello guys,
M new to bash scripting and i wish to search all text files present on local disk. But m unable to write correct script for it. Please help me....

gilead 02-19-2008 12:29 AM

It's worth having a look at the advanced bash scripting guide - it's a very useful document.

You can use grep to do what you want and you can call it a couple of ways. If you just want to search for a string in every single file:
Code:

grep -r 'search-string' /*
Or, if you only want to search particular files or locations, use the find command:
Code:

find / -type f -name '*java' -exec grep 'search-string' {} \;
or
find / -type f -name '*java' | xargs grep 'search-string'

I can't test those at the moment, so beware of typos...

elluva 02-19-2008 12:14 PM

usually I use:
find <dir> -exec grep -l {} \;

the -l option to grep makes that grep only returns the filename and not the line it found in the file. If you don't use this option, you have all these lines, but you don't know which file it comes from.

archtoad6 02-19-2008 01:14 PM

Don't forget that if you're searching for a fixed string, rather than a regex, the grep "-F" can speed things up a lot.


BTW, gilead, that is a very thoughtful warning, thanks. :)

sudowtf 06-23-2015 11:43 AM

concerning "grep -r", i would use "grep -Ir" to ignore binary files.

Keith Hedger 06-23-2015 02:31 PM

I have this
Code:

alias search='find . \! -iname '\''*~'\'' -print |xargs grep -s --ignore-case --binary-files=without-match --line-number'
In my bashrc file so I just use
Code:

search searchterm
when in the terminal.


All times are GMT -5. The time now is 09:17 AM.