Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

search and replace string on multiple files from unix terminal

Tags:

We are converting all the static html pages in our codebase into php pages. The first step would be to change all the .html file extension to .php (which I already did). The second step would be to update all the links within each of those html pages to point to new php pages.

(for instance, inside index.php i have links to both contact.html and about-us.html. Now since we have replaced every .html file extension to .php, we need to change contact.html to contact.php, and likewise, about-us.html to about-us.php).

what i want to do now is to search for a particular string across multiple files. (search for "contact.html" inside many files, such as index.php, index2.php, index3.php, etc etc..) after that, replace all "contact.html" in all those files with "contact.php".

I am not familiar with unix command line, and i so far have seen other people's similar questions here in the forum but not quite understand which one could help me achieve what i want. I'm using cygwin and if possible i need to solve this without perl script since i dont have it installed. i need to try using either sed, grep, find, or anything else.

So, if any of you think that this is a duplicate please point me to a relevant post out there. thanks for your time.

like image 456
Benny Tjia Avatar asked Sep 24 '11 00:09

Benny Tjia


People also ask

How do I find and replace text in multiple files?

Remove all the files you don't want to edit by selecting them and pressing DEL, then right-click the remaining files and choose Open all. Now go to Search > Replace or press CTRL+H, which will launch the Replace menu. Here you'll find an option to Replace All in All Opened Documents.

How do I search for a string in multiple files in Unix?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.


2 Answers

Try this:

find . -name '*.html' -exec sed -i 's/\.html/\.php/g' "{}" \;

It will find all files in the current and subdirectories that end in .html, and run sed on each of them to replace .html with .php anywhere it appears within them.

See http://content.hccfl.edu/pollock/unix/findcmd.htm for more details.

like image 138
Adam Liss Avatar answered Oct 22 '22 10:10

Adam Liss


On my Mac, I had to add a parameter to the -i option: the extension to add to the name (in this case, nothing, so the file is stored in-place).

find . -name '*.html' -exec sed -i '' 's/\.html/\.php/g' "{}" \;
like image 40
Fabruccio Avatar answered Oct 22 '22 10:10

Fabruccio