Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace a URL with grep/sed/awk?

Tags:

grep

replace

Fairly regularly, I need to replace a local url with a live in large WordPress databases. I can do it in TextMate, but it often takes 10+ minutes to complete.

Basically, I have a 10MB+ .sql file and I want to:

  • Find: http://localhost:8888/mywebsite
  • And replace with: http://mywebsite.com

After that, I'll save the file and do a MySQL import to the local/live servers. I do this at least 3-4 times a week and waiting for TextMate has been a pain.

Is there an easier/faster way to do this with grep/sed/awk?

like image 703
saltcod Avatar asked Apr 16 '26 06:04

saltcod


2 Answers

sed 's/http:\/\/localhost:8888\/mywebsite/http:\/\/mywebsite.com/g' FileToReadFrom > FileToWriteTo

This is running switch (s/) globally (/g) and replacing the first URL with the second. Forward slashes are escaped with a backslash.

like image 52
Jared Avatar answered Apr 25 '26 13:04

Jared


kent$  echo "foobar||http://localhost:8888/mywebsite||fooooobaaaaaaar"|sed 's#http://localhost:8888/mywebsite#http://mywebsite.com#g'
foobar||http://mywebsite.com||fooooobaaaaaaar

if you want to do the replace in place (change in your original file)

sed -i 's#http://.....#http://mysite#g' input.sql
like image 23
Kent Avatar answered Apr 25 '26 15:04

Kent