You are used to work with rich IDEs like Eclipse, or you use powerful file manager like Konqueror and searching in the current directory/project files for a given content is an easy task… But imagine that you are on a remote headless machine and you need to do the same thing there… For example you are searching for an IP address inside all the files and sub-directory files of the /etc folder. How are you going to do this?
- Use the grep command. Navigate to the directory you want to search in and execute the following command:
grep -iRn "<expression-you-are-searching-for>" *
This will search in all the files in the current directory recursively for the expression and will list the line containing the expression along with the name of the file containing it and the line number.
– The -i option tells grep to ignore the case of the expression (so if you want case sensitive search, exclude it)
– The -R option tells the command to search all the files and sub-directories in the passed directory recursively.
– The -n option tells grep to show the line numbers of the lines matched.
– The last parameter of the command (‘*’ in the example) is glob, so you can search only in C source files by setting it to ‘*.c’, for example.
- If you insist you can use find (again with grep)…
find . -iname "*.html" -print | xargs grep -i "Some"
- You can use ack (brew install ack / sudo apt-get install ack).
– On some systems the program is called ‘ack-grep’ so you can add this to your .bashrc file : alias ack=ack-grep
– Here is the command:
ack --nogroup -i "<expression>"
– Here the –nogroup options turns off the grouping of the results by files.
– The -i option is for ignoring the case.
I personally prefer using ack.
Now if you want to integrate for example the ack search with vim and for example to search for a method use in a rails project using your editor you can add these in your ‘.vimrc’ :
set grepprg=ack\ --nogroup\ --column set grepformat=%f:%l:%c:%m
- This will replace the default vim ‘grep’ command with our command.
- You can create similar configuration with grep, try it.
- In the grepformat:
– %f is filename
– %l is line number
– %c is column number
– %m is message or matched content in our case
- Now if you run Vim and execute :grep “<expression>”, the current working directory will be recursively searched for the files containing the expression using ack.
- After the search you can execute :copen to be able to browse the search result and navigate in the listed files.
- After you are done searching/browsing, execute :cclose to close the search results.
So this is it for this post…