Find Text and Find/Replace Easier Than You Think in Linux

How to search all files for a text string:

grep -lr string ./ > results.txt

-l will print only the path and file names of the matches.

Search all files of a certain name for a certain string:

grep -lr string ./ | grep filename

Yes, do specify ./ if you are doing all directories within current.

(source and more info)

Find an replace a string in files:
Searching for a way to do this usually leads me to finding fancy scripts that don’t work right, are scary (create temp files, etc) or aren’t recursive. Just have backups at hand and test the following combination of find and sed before unleashing it, because it works great! You can test it by replacing sed with grep

find ./ -type f -exec sed -i ’s/string1/string2/’ {} \;

Within specific file names/extentions…

find ./ -iname \*.htm\* -exec sed -i 's/\-2005/\-2007/g' {} \;

Don’t forget to use escape \ as seen above. And if your strings contain forward slash / just use a different delimiter such as pipe | or escape it.

You can also install rpl, as shown in the source pdf, for even cleaner line of code for executing your find and replace.

(source and more info) A nice pdf to keep by your side.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

This entry was posted in quickfire, tips and tagged , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

One Comment

  1. Posted October 25, 2009 at 11:53 am | Permalink

    Nice post. I’ve found myself needing to search inside files often recently, and grep has came in very handy.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>