Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Search and Replace across multiple files in linux

Olivia Rhye

I had a group of files today that had a wrong link in them. I started changing them one-by-one until I realized how many files there were. I immediately knew I needed a way to search and replace the link across all these files, something I didn't know was possible with a linux command. While technically you need 2 commands, there is a way to accomplish this.

I needed to change a link listed as "index.html" to "/admin". I knew how to search in replace inside of Vim:


s/index.html/\/admin/g

Note the backslash to tell the command line the forward slash in "/admin" is not part of the command language. But how do I run this command on all files? Well first we need to get all files that have the "index.html" link. Grep is nice for that:


grep -lr -e 'index.html' *

Now the part that I hadn't realized before is, I can take the results of that search and run a command on each of those files. This is where the xargs command comes in:


xargs sed -i 's/index.html/\/admin/g'

So we can combine both of our commands with a pipe:


grep -lr -e 'index.html' * | xargs sed -i 's/index.html/\/admin/g'

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy