Archive for the ‘Power Tools’ Category

The Nautilus file manager in Ubuntu features a search-for-document tool for quite a long time. However, its functionality is quite limited as it allows the user to search only for file name, but not the contents of the file. Personally, I was quite shocked because the ability to search for file contents has been available in its Microsoft counterparts since Windows 98.

Apparently, Linux users are more proficient at the command line. Grep is a command line tool that allows the user to search for specific pattern or text, given lines from the standard input or a file. Once you know grep, searching the content of files will become so easy as never before.

To search in a single file, use the following command. (Please do not type in the ‘$’, which is the prompt symbol for a terminal).

$ grep "Search text" filename.txt

Typically, we would like to look up the file contents of the whole directory. We can use the -r option to search recursively under a directory and use the -l option to suppress printing every matched lines and printing only the matching file names.

$ grep -r -l "Search text" dir

Or instead, if we wish to print every lines, the -n option can be used to print line numbers.

$ grep -r -n "Search text" dir

Besides, grep supports the use of regular expression by passing it the following options: -G (Basic RegExp), -E (Extended RegExp), and -P (Perl RegExp).

Below are some other usage of grep, which uses piping, i.e taking the output of another command and directing it back into the standard input, so that grep can search within the output. Some of us probably have known these commands before digging deep into grep, since these commands are so widely use.

$ lspci | grep 'Network'
$ egrep '(vmx|svm)' /proc/cpuinfo
$ ls -l | grep rwxrwxrwx
$ ps -A | grep -i firefox
$ du | grep 'mp3' | more
$ dmesg | egrep '(s|h)d[a-z]'
$ ps -ef | egrep '^root ' | awk '{print $2}'
$ lsof | grep -i TCP
$ lsof | grep ' root ' | awk '{print $NF}' | sort | uniq | wc -l

Finally, I would leave it for you, the reader, to figure out what each the above command does.