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 asinput_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:
<p>\(.*\)<\/p>
: The regex pattern captures the content inside the<p>
tags using the capture group\(.*\)
.<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.