A memorable way to Find and Replace recursively

So yeah, getting used to Bash is about finding the right way to do things. However, learning one-liners and picking up information here and there is all very useful, finding something you don't need to Google in order to recall is extremely important.

Take the case of recursive find and replace. We've all been there, it needs to be done frequently but you're either a) scared or b) forgetful. Then you use the same snippet from a web resource again and again and eventually make a serious error and boom, simplicity is now lost on you!

So here it is, something you can remember so that you don't use different methods depending on what Google throws up today.

grep -Rl newertext . | xargs sed -i 's/newertext/newesttext/g'

Notice, we use grep to search -R recursively with results fed to xargs which does a simple sed replace with g global/infinite properties.

Say you want to keep it simple though and find and review the files before doing the "simple" replace. Well, do this.

grep -R -l "foo" ./*

The uppercase -R denotes to follow symlinks and the ./* indicates the current directory. The -l requests a list of filenames matched. Neat.


Related posts

Published by

Linux Bash

Linux Bash

Providing immersive and explanatory content in a simple way anybody can understand.