Friday, 18 November 2011 21:40
A few days ago a friend of mine asked me how he could find some text which was in a file in his system. The problem was that he didn't know which file that was so he had to search his whole filesystem. So, here are a couple of simple ways to do this in Linux through command line.
As an example I have two files called distros1 and distros2. Both of them are inside a directory called test. I am going to search for the word ubuntu in all files of test directory.
$ cat test/distros1 ubuntu fedora archlinux $ cat test/distros2 debian gentoo mint opensuse
The first command is
find <directory to search> -type f | xargs grep -rl '<text to search for>'
Example:
$ find /home/axel/test/ -type f | xargs grep -rl 'ubuntu' /home/axel/test/distros1
The second command which also works fine with pathnames cotaining blanks and quotes is
find <directory to search> -type f -exec grep -l ‘<text to search for>’ {} +
Example:
$ find /home/axel/test/ -type f -exec grep -l 'ubuntu' {} +
/home/axel/test/distros1
The third command is
grep -rl ‘<text to search for>’ <directory to search>/*
Example:
$ grep -rl 'ubuntu' /home/axel/test/* /home/axel/test/distros1
That was all, a quick and sometimes useful tip!