Skip to content

Instantly share code, notes, and snippets.

@devtooligan
Created March 18, 2025 20:36
Show Gist options
  • Save devtooligan/b6d2eccb6c27d701c1747d66f5202204 to your computer and use it in GitHub Desktop.
Save devtooligan/b6d2eccb6c27d701c1747d66f5202204 to your computer and use it in GitHub Desktop.
convert .md to string (with properly escaped characters)
import sys
import re
def convert_to_ts_string(file_path):
try:
# Read the Markdown file content
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
# Escape special characters
# Escape backslashes first (to avoid double-escaping)
content = content.replace('\\', '\\\\')
# Escape double quotes
content = content.replace('"', '\\"')
# Convert newlines to \n
content = content.replace('\n', '\\n')
# Return just the escaped content
return content
except FileNotFoundError:
return f"Error: File '{file_path}' not found"
except Exception as e:
return f"Error: {str(e)}"
def main():
# Check if file path is provided as command line argument
if len(sys.argv) != 2:
print("Usage: python script.py <path_to_md_file>")
sys.exit(1)
file_path = sys.argv[1]
# Convert the file and print the result
result = convert_to_ts_string(file_path)
print(result)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment