- Posted on
- • Command Line Interface
A memorable way to Find and Replace recursively
- Author
-
-
- User
- Linux Bash
- Posts by this author
- Posts by this author
-
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.
Further Reading
For further reading and to deepen your understanding of text manipulation and command line utilities in Linux, consider exploring the following resources:
Advanced Bash-Scripting Guide: An in-depth exploration of scripting using Bash, including file operations. http://www.tldp.org/LDP/abs/html/
GNU grep and sed: Official documentation providing detailed usage of
grep
andsed
. https://www.gnu.org/software/grep/manual/grep.html https://www.gnu.org/software/sed/manual/sed.htmlLinux Command Line and Shell Scripting Bible: Comprehensive guide to mastering the command line and writing shell scripts. https://www.wiley.com/en-us/Linux+Command+Line+and+Shell+Scripting+Bible%2C+3rd+Edition-p-9781118983843
Unix Power Tools: Covers hundreds of tips, tricks, and techniques at your disposal with Unix/Linux systems. https://www.oreilly.com/library/view/unix-power-tools/0596003307/
Practical Guide to Linux Commands, Editors, and Shell Programming: A hands-on guide to using Linux effectively for beginners and experienced users. https://www.pearson.com/store/p/practical-guide-to-linux-commands-editors-and-shell-programming-a/P100000648086/9780134277554
These resources will help enhance your proficiency in handling complex text-editing tasks within the Linux environment.