Automatically Change Links from Absolute to Relative

In this example I'm showing one way to quickly convert all a href and img src paths from absolute to relative. It's quite a time saver, but I suggest commiting your latest changes before trying anything here! If you aren't using a version control system, make a backup somewhere... please!

Note: Both of these commands are one-liners.

#BSD Version (Mac):
find . -path './.git' -prune -o -type f -exec sed -i '' -E "s/(href|src) *= *([\"'])(https?:\/\/)?(www\.)?mysite\.(org|com)\//\1=\2\//g" {} \;

#GNU Version:
find . -path './.git' -prune -o -type f -exec sed -i -r "s/(href|src) *= *([\"'])(https?:\/\/)?(www\.)?mysite\.(org|com)\//\1=\2\//g" {} \;

#You may consider using    {} +;    instead of    {} \;
In the examples/results below, I tried to target most situations. You should see subtle differences between each example.
-<a href = "https://www.mysite.org/basic_skills">This is another link</a>
+<a href="/basic_skills">This is another link</a>

-<a href ="https://www.mysite.org/basic_skills">This is another link</a>
+<a href="/basic_skills">This is another link</a>

-<a href="http://www.mysite.org/basic_skills">This is another link</a>
+<a href="/basic_skills">This is another link</a>

-<a href="http://mysite.org/basic_skills">This is another link</a>
+<a href="/basic_skills">This is another link</a>

-<a href='www.mysite.org/basic_skills'>This link points to http://www.mysite.org/basic_skills</a>
+<a href='/basic_skills'>This link points to http://www.mysite.org/basic_skills</a>

-<a href="mysite.org/basic_skills">This is another link</a>
+<a href="/basic_skills">This is another link</a>

-<a href="http://www.mysite.com/basic_skills">This is the last link</a>
+<a href="/basic_skills">This is the last link</a>

-<img src="http://www.mysite.org/testing123.jpg" />
+<img src="/testing123.jpg" />

Tags: 

Add new comment