diff --git a/pkg/yqlib/doc/String Operators.md b/pkg/yqlib/doc/String Operators.md index 1a551816..1c3d0b93 100644 --- a/pkg/yqlib/doc/String Operators.md +++ b/pkg/yqlib/doc/String Operators.md @@ -20,6 +20,7 @@ cat; meow; 1; ; true ## Substitute / Replace string This uses golang regex, described [here](https://github.com/google/re2/wiki/Syntax) +Note the use of `|=` to run in context of the current string value. Given a sample.yml file of: ```yaml @@ -36,6 +37,7 @@ a: cats are great ## Substitute / Replace string with regex This uses golang regex, described [here](https://github.com/google/re2/wiki/Syntax) +Note the use of `|=` to run in context of the current string value. Given a sample.yml file of: ```yaml @@ -44,7 +46,7 @@ b: heat ``` then ```bash -yq eval '.[] |= sub("([a])", "${1}r")' sample.yml +yq eval '.[] |= sub("(a)", "${1}r")' sample.yml ``` will output ```yaml diff --git a/pkg/yqlib/operator_strings.go b/pkg/yqlib/operator_strings.go index 5b2f5f0d..bca8e237 100644 --- a/pkg/yqlib/operator_strings.go +++ b/pkg/yqlib/operator_strings.go @@ -62,7 +62,7 @@ func substituteStringOperator(d *dataTreeNavigator, context Context, expressionN candidate := el.Value.(*CandidateNode) node := unwrapDoc(candidate.Node) if node.Tag != "!!str" { - return Context{}, fmt.Errorf("cannot sustitute with %v, can only substitute strings", node.Tag) + return Context{}, fmt.Errorf("cannot substitute with %v, can only substitute strings. Hint: Most often you'll want to use '|=' over '=' for this operation.", node.Tag) } targetNode := substitute(node.Value, regEx, replacementText) diff --git a/pkg/yqlib/operator_strings_test.go b/pkg/yqlib/operator_strings_test.go index dd7d9358..1b67eee5 100644 --- a/pkg/yqlib/operator_strings_test.go +++ b/pkg/yqlib/operator_strings_test.go @@ -15,7 +15,7 @@ var stringsOperatorScenarios = []expressionScenario{ }, { description: "Substitute / Replace string", - subdescription: "This uses golang regex, described [here](https://github.com/google/re2/wiki/Syntax)", + subdescription: "This uses golang regex, described [here](https://github.com/google/re2/wiki/Syntax)\nNote the use of `|=` to run in context of the current string value.", document: `a: dogs are great`, expression: `.a |= sub("dogs", "cats")`, expected: []string{ @@ -24,9 +24,9 @@ var stringsOperatorScenarios = []expressionScenario{ }, { description: "Substitute / Replace string with regex", - subdescription: "This uses golang regex, described [here](https://github.com/google/re2/wiki/Syntax)", + subdescription: "This uses golang regex, described [here](https://github.com/google/re2/wiki/Syntax)\nNote the use of `|=` to run in context of the current string value.", document: "a: cat\nb: heat", - expression: `.[] |= sub("([a])", "${1}r")`, + expression: `.[] |= sub("(a)", "${1}r")`, expected: []string{ "D0, P[], (doc)::a: cart\nb: heart\n", },