Search and Replace across multiple files in linux
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:
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'