14 Feb 16 - 12:46
grep is a wonderful tool that I think those new to Linux should really come to grips with.
Essentially, it allows you to search for strings. Simple as that. However, I recently discovered that grep can also be used to search for strings in files in folders.
i.e. if you’ve got a folder full of text files and you’re looking for one containing a specific string; use grep!
grep -r 'string you're searching for' /directory/to/search/in
example of me trying to find files still containing the string ‘dev.journeyatrest.com’ that I use in my development environment:
grep -r 'dev.journeyatrest.com' post/index.php: <div data-easyshare data-easyshare-url="http://dev.journeyatrest.com/post/index.php?id='.$related[$k]['id'].'"> drafts/index.php: header("location:http://dev.journeyatrest.com/editor/login.php"); editor/auto_save.php: header("location:http://dev.journeyatrest.com/editor/"); editor/edit/index.php: header("location:http://dev.journeyatrest.com/editor/login.php");
Or you can omit the directory and it will search in the currently active directory. -r just means recursive; so it will search through sub directories as well.
If you limit your results to match only file names using -l.
grep -rl 'string you're searching for' /directory/to/search/in
grep -rl 'dev.journeyatrest.com' post/index.php drafts/index.php editor/auto_save.php editor/edit/index.php
You can take this further and pipe the result to sed. sed can then use the results from a grep -rl to replace the string you’re searching for with another string.
grep -rl 'dev.journeyatrest.com' | xargs sed -i 's/dev.journeyatrest.com/kyluke.kyco.io/g'
The syntax ’s/dev.journeyatrest.com/kyluke.kyco.io/g’ is simple. *\’s/original string/new string to replace/g\’*. s and g are best covered by vim tutorials.