Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@rmoff
Created March 17, 2023 12:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rmoff/3196edc5942ab29c3def09e290270642 to your computer and use it in GitHub Desktop.
Save rmoff/3196edc5942ab29c3def09e290270642 to your computer and use it in GitHub Desktop.
Raycast AI helping with regex

rmoff: mac regex replace in file from CLI

Raycast AI: You can use the sed command on macOS to perform a regex replacement in a file from the command line. Here's the general syntax:

sed 's/regex/replacement/g' input_file > output_file
  • regex: The regular expression you want to search for.
  • replacement: The text you want to replace the matched regex with.
  • input_file: The file you want to perform the replacement in.
  • output_file: The file where you want to save the result. You can use the same file as input_file to perform an in-place replacement.

For an in-place replacement, you can use the -i flag with an optional backup file extension:

sed -i '.backup' 's/regex/replacement/g' input_file

This will replace the contents of input_file and create a backup file with the .backup extension.


rmoff: how would I do that with HTML in the regex?

Raycast AI: If you want to use HTML in the regex, you need to escape special characters like <, >, and / with a backslash (\). Here's an example that replaces all occurrences of <p> with <div> and </p> with </div> in an HTML file:

sed 's/<p>/<div>/g; s/<\/p>/<\/div>/g' input_file.html > output_file.html

This command performs two replacements: one for <p> and another for </p>. The two replacements are separated by a semicolon (;). Remember to escape the forward slash (/) in the closing tag with a backslash (\).


rmoff: does this work with a capture group?

Raycast AI: Yes, you can use capture groups with sed by using parentheses () and referencing them with \1, \2, etc., depending on the order of the capture groups. Here's an example that wraps text inside <p> tags with <div> tags:

sed 's/<p>\(.*\)<\/p>/<div><p>\1<\/p><\/div>/g' input_file.html > output_file.html

In this example:

  1. <p>\(.*\)<\/p>: The regex pattern captures the content inside the <p> tags using the capture group \(.*\).
  2. <div><p>\1<\/p><\/div>: The replacement pattern uses \1 to reference the captured content and wraps it with <div> tags.

This command will replace occurrences of <p>content</p> with <div><p>content</p></div> in the input file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment