replace-file-content
Learn how to replace content in files using patterns.
This action replaces content in files using regular expression patterns.
All occurrences of each pattern are replaced, and replacements are applied sequentially within each file, so later replacements operate on the result of earlier ones.
Example
The following template updates the project name in a configuration file:
{ "$schema": "https://schema.croct.com/json/v1/template.json", "title": "Config updater", "description": "Updates the project name in the config file.", "options": { "name": { "type": "string", "description": "The project name.", "default": "my-app" } }, "actions": [ { "name": "replace-file-content", "files": [ { "path": "config.json", "replacements": [ { "pattern": "\"name\": \".*\"", "value": "\"name\": \"${options.name}\"" } ] } ] } ]}To apply this template, run:
npx croct@latest use template.json5 --name my-appCapture groups
Use capture groups in the pattern to reference matched segments in the replacement value with $1, $2, and so on:
{ "$schema": "https://schema.croct.com/json/v1/template.json", "title": "Import updater", "description": "Rewrites import paths.", "actions": [ { "name": "replace-file-content", "files": [ { "path": "src/index.ts", "replacements": [ { "pattern": "from ['\"]@/lib/(.*)['\"]", "value": "from '@/utils/$1'" } ] } ] } ]}All imports from @/lib/ are rewritten to @/utils/, preserving the original module name through the $1 reference.
Properties
These are the supported properties:
- namestring
The action identifier. Always replace-file-content for this action.
- filesArray<object>
The list of files to process.
Each entry specifies a file path and the replacements to apply. The action fails if no files match.
- pathstring
The path to the file.
- replacementsArray<object>
The list of replacements to apply in order.
- patternstring
The regular expression to match.
Capture groups like $1 and $2 can be referenced in the replacement value.
- valuestring|number
The replacement value.
- caseSensitive(optional)boolean
Whether to ignore case when matching.
When enabled, the pattern matches regardless of letter casing.
Default:false
- pattern
- path