yq/pkg/yqlib/doc/operators/headers/string-operators.md

58 lines
1.6 KiB
Markdown
Raw Normal View History

2021-01-14 04:05:50 +00:00
# String Operators
2021-07-09 05:33:41 +00:00
## RegEx
2022-04-01 02:21:55 +00:00
This uses golangs native regex functions under the hood - See their [docs](https://github.com/google/re2/wiki/Syntax) for the supported syntax.
Case insensitive tip: prefix the regex with `(?i)` - e.g. `test("(?i)cats)"`.
2021-08-01 08:47:04 +00:00
2022-03-22 23:28:45 +00:00
### match(regEx)
This operator returns the substring match details of the given regEx.
### capture(regEx)
Capture returns named RegEx capture groups in a map. Can be more convenient than `match` depending on what you are doing.
2022-04-01 02:21:55 +00:00
## test(regEx)
2022-03-22 23:28:45 +00:00
Returns true if the string matches the RegEx, false otherwise.
## sub(regEx, replacement)
Substitutes matched substrings. The first parameter is the regEx to match substrings within the original string. The second is a what to replace those matches with. This can refer to capture groups from the first RegEx.
2021-08-01 08:47:04 +00:00
2021-11-03 04:00:58 +00:00
## String blocks, bash and newlines
2021-08-01 08:47:04 +00:00
Bash is notorious for chomping on precious trailing newline characters, making it tricky to set strings with newlines properly. In particular, the `$( exp )` _will trim trailing newlines_.
For instance to get this yaml:
```
a: |
cat
```
Using `$( exp )` wont work, as it will trim the trailing new line.
```
2022-01-27 06:21:10 +00:00
m=$(echo "cat\n") yq -n '.a = strenv(m)'
2021-08-01 08:47:04 +00:00
a: cat
```
However, using printf works:
```
2022-01-27 06:21:10 +00:00
printf -v m "cat\n" ; m="$m" yq -n '.a = strenv(m)'
2021-08-01 08:47:04 +00:00
a: |
cat
```
As well as having multiline expressions:
```
m="cat
2022-01-27 06:21:10 +00:00
" yq -n '.a = strenv(m)'
2021-08-01 08:47:04 +00:00
a: |
cat
```
Similarly, if you're trying to set the content from a file, and want a trailing new line:
```
IFS= read -rd '' output < <(cat my_file)
2022-01-27 06:21:10 +00:00
output=$output ./yq '.data.values = strenv(output)' first.yml
2021-11-03 04:00:58 +00:00
```