str replace for strings

Find and replace text.

Signature

> str replace {flags} (find) (replace) ...rest

Flags

  • --all, -a: replace all occurrences of the pattern
  • --no-expand, -n: do not expand capture groups (like $name) in the replacement string
  • --regex, -r: match the pattern as a regular expression in the input, instead of a substring
  • --multiline, -m: multi-line regex mode (implies --regex): ^ and $ match begin/end of line; equivalent to (?m)

Parameters

  • find: The pattern to find.
  • replace: The replacement string.
  • ...rest: For a data structure input, operate on strings at the given cell paths.

Input/output types:

inputoutput
list<string>list<string>
recordrecord
stringstring
tabletable

Examples

Find and replace the first occurrence of a substring

> 'c:\some\cool\path' | str replace 'c:\some\cool' '~'
~\path

Find and replace all occurrences of a substring

> 'abc abc abc' | str replace --all 'b' 'z'
azc azc azc

Find and replace contents with capture group using regular expression

> 'my_library.rb' | str replace -r '(.+).rb' '$1.nu'
my_library.nu

Find and replace all occurrences of find string using regular expression

> 'abc abc abc' | str replace --all --regex 'b' 'z'
azc azc azc

Find and replace all occurrences of find string in table using regular expression

> [[ColA ColB ColC]; [abc abc ads]] | str replace --all --regex 'b' 'z' ColA ColC
╭───┬──────┬──────┬──────╮
 # │ ColA │ ColB │ ColC │
├───┼──────┼──────┼──────┤
 0  azc   abc   ads  
╰───┴──────┴──────┴──────╯

Find and replace all occurrences of find string in record using regular expression

> { KeyA: abc, KeyB: abc, KeyC: ads } | str replace --all --regex 'b' 'z' KeyA KeyC
╭──────┬─────╮
 KeyA  azc 
 KeyB  abc 
 KeyC  ads 
╰──────┴─────╯

Find and replace contents without using the replace parameter as a regular expression

> 'dogs_$1_cats' | str replace -r '\$1' '$2' -n
dogs_$2_cats

Use captures to manipulate the input text using regular expression

> "abc-def" | str replace -r "(.+)-(.+)" "${2}_${1}"
def_abc

Find and replace with fancy-regex using regular expression

> 'a successful b' | str replace -r '\b([sS])uc(?:cs|s?)e(ed(?:ed|ing|s?)|ss(?:es|ful(?:ly)?|i(?:ons?|ve(?:ly)?)|ors?)?)\b' '${1}ucce$2'
a successful b

Find and replace with fancy-regex using regular expression

> 'GHIKK-9+*' | str replace -r '[*[:xdigit:]+]' 'z'
GHIKK-z+*

Find and replace on individual lines using multiline regular expression

> "non-matching line\n123. one line\n124. another line\n" | str replace --all --multiline '^[0-9]+\. ' ''
non-matching line
one line
another line