This script is an evolution of the “search and replace” feature from text editor,
where the “replace” step has been replaced by a LLM transformation.
It can be useful to batch apply text transformations that are not easily done with
regular expressions.
For example, when GenAIScript added the ability to use a string command string in
the exec command, we needed to convert all script using
to
While it’s possible to match this function call with a regular expression
it’s not easy to formulate the replacement string… unless you can describe it in natural language:
Here are some example of the transformations where the LLM correctly handled variables.
concatenate the arguments of a function call into a single string
concatenate the arguments and use the ${} syntax to interpolate variables
Search
The search step is done with the workspace.grep
that allows to efficiently search for a pattern in files (this is the same search engine
that powers the Visual Studio Code search).
Compute Transforms
The second step is to apply the regular expression to the file content
and pre-compute the LLM transformation of each match using an inline prompt.
Since the LLM sometimes decides to wrap the answer in quotes, we need to remove them.
Transform
Finally, with the transforms pre-computed, we apply a final regex replace to
patch the old file content with the transformed strings.
Parameters
The script takes three parameters: a file glob, a pattern to search for, and a LLM transformation to apply.
We declare these parameters in the script metadata and extract them from the env.vars object.
Full source
To run this script, you can use the --vars option to pass the pattern and the transform.