W3cubDocs

/Nushell

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:

input output
list<string> list<string>
record record
string string
table table

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-a'b''z'
azcazcazc

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-ar'b''z'
azcazcazc

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

> [[ColAColBColC]; [abcabcads]] |str replace-ar'b''z'ColAColC
╭───┬──────┬──────┬──────╮
# │ ColA │ ColB │ ColC │
├───┼──────┼──────┼──────┤
0azcabcads
╰───┴──────┴──────┴──────╯

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

> { KeyA:abc, KeyB:abc, KeyC:ads } |str replace-ar'b''z'KeyAKeyC
╭──────┬─────╮
KeyAazc
KeyBabc
KeyCads
╰──────┴─────╯

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'
asuccessfulb

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-am'^[0-9]+\. '''
non-matchingline
oneline
anotherline

Copyright © 2019–2023 The Nushell Project DevelopersLicensed under the MIT License.
https://www.nushell.sh/commands/docs/str_replace.html