Grep
From TWUUG
grep is a very powerful multi-purpose program because it allows you to search the contents of a single, multiple files or the output of a command. Lets do a few examples to shows the various functions.
- searching a single file - the syntax for searching a single file is "cat {file name}|grep {word}". Go ahead and type "cat /etc/inittab|grep default", this will use the cat function to display the contents of the /etc/inittab file and send the output through grep which will only display lines with the word default.
user@linux:/$ cat /etc/inittab|grep default # These are the default runlevels in Slackware: # 3 = multiuser mode (default Slackware runlevel) id:4:initdefault:
- searching the output of a command - the syntax for searching the output of a command is "{program syntax}|grep {word}". For an example I will use the ls command to get the list of files in my /etc directory and use grep to only display the fies with the word tab in the name, the command is "ls /etc|grep tab", the output is shown below.
user@linux:/# ls /etc/|grep tab blkid.tab blkid.tab.old bootptab crypttab fstab fstab~ inittab inittab~ mtab
- Searching the contents of files in a single directory - The syntax for this search is "grep {word} *". As an example I am going to be in my /etc directory and search for the word lilo using grep, I will type "grep lilo *", the output is below.
user@linux:/etc$ grep lilo * lilo.conf:# generated by 'liloconfig' lilo.conf~:# generated by 'liloconfig'
- Search the contents of files in many directories - The syntax for this search is "grep -R {word} {directory}*". As an example I will show you how to search for the word linux in your entire system, type "sudo -R linux /*", the -R tells grep to search recursively or search all underlying directories, / is the root directory were you want to start and the * is telling you to search all files in that directory. The output is omitted because it is too large.