Skip to content

Instantly share code, notes, and snippets.

@sandipb
Created February 29, 2024 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sandipb/7777b733bb91124c38bdd4cd9bf9c604 to your computer and use it in GitHub Desktop.
Save sandipb/7777b733bb91124c38bdd4cd9bf9c604 to your computer and use it in GitHub Desktop.
Python script to pipe text with short urls and have it expand short urls in it
import re
import sys
import requests
def expand_url(match):
short_url = match.group(0)
response = requests.head(short_url, allow_redirects=False)
if response.status_code in (301, 302):
return response.headers["location"]
else:
return short_url
pattern = r"https://(t\.co|bit\.ly)/[a-zA-Z0-9]+"
if __name__ == "__main__":
text = sys.stdin.read().strip()
expanded_text = re.sub(pattern, expand_url, text)
print(expanded_text)

Example output:

$ echo This is a long text with an url https://t.co/osibkgbKtI | python expand_short_url.py
This is a long text with an url https://twitter.com/shaderapp/status/1762912396077883415

$ echo A nice quote: https://bit.ly/33ToHFx  | python expand_short_url.py
A nice quote: https://www.goodreads.com/quotes/1716
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment