Tuesday, October 30, 2012

Searching inside files with grep

  • The “grep” command can be used to search inside files.

                                $ grep word filename
        
         Ex: to find the lines having the word "File" inside a file named foo.txt


  • if you need to match the whole word use the -w option with grep
                             $ grep -w 'word' filename

       Ex: in the previous example even though you searched for the word "File" other words which contain the word "File" as a part of it also got selected.by using -w option we can avoid that


      Ex: i have a file named yumlist.txt containing names of packages,and there are thousands of package names in that file.i need to find the package gcj from that file.if i just search using grep other packages which has gcj as a part of its name will also get selected(eg:-libgcj) , but when i use grep with -w option only the gcj packages will get selected
    

  • to ignore case use -i option
         Ex:the word "File" in the file foo.txt starts with a capital "F" ,if i just  search as "file" no line will get selected, but when -i option is used, grep will ignore the case and select the lines.
 
          


  • to recursively search files in current directory and all its sub directories use the “grep” command with -r option
   Ex : i need to find if there are any servlet source code files present in the current directory or any of its sub directories.


  • to display the line numbers of the lines containing the matching word use -n option

  • to list only the file names of the files containing the matching word use the -l option with grep

  • grep can also be used to search inside outputs generated by other commands using a pipe

                           $ command | grep 'word'
   
                 Ex : I'm in the directory /usr/bin and i need to find all the icewm files in that directory.
                        if i just type ls 3626 files will be displayed



               so i direct the output of ls command to a grep command and search for icewm files




  • you can also use regular expressions when searching using the “grep” command
            
                                    $ grep “regular expression” filename

                                                                  or

                                   $ grep -e “regular expression” filename

                                                           or

                                  $ grep --regexp=“regular expression” filename

Ex: website1.sql is a backup file of an sql database having data on customers,items,orders,purchases,etc . i need to find the customer email addresses ending with a .com from that file.



if you want to learn more on using regular expressions using grep click here

No comments:

Post a Comment