Working with strings

Strings in Nushell help to hold text data for later use. This can include file names, file paths, names of columns, and much more. Strings are so common that Nushell offers a couple ways to work with them, letting you pick what best matches your needs.

String formats at a glance

Format of stringExampleEscapesNotes
Single-quoted string'[^\n]+'NoneCannot contain any '
Backtick string`[^\n]+`NoneCannot contain any backticks `
Double-quoted string"The\nEnd"C-style backslash escapesAll backslashes must be escaped
Bare stringozymandiasNoneCan only contain "word" characters; Cannot be used in command position
Single-quoted interpolation$'Captain ($name)'NoneCannot contain any ' or unmatched ()
Double-quoted interpolation$"Captain ($name)"C-style backslash escapesAll backslashes and () must be escaped

Single-quoted strings

The simplest string in Nushell is the single-quoted string. This string uses the ' character to surround some text. Here's the text for hello world as a single-quoted string:

> 'hello world'
hello world
> 'The
end'
The
end

Single-quoted strings don't do anything to the text they're given, making them ideal for holding a wide range of text data.

Backtick-quoted strings

Single-quoted strings, due to not supporting any escapes, cannot contain any single-quote characters themselves. As an alternative, backtick strings using the ` character also exist:

> `no man's land`
no man's land
> `no man's
land`
no man's
land

Of course, backtick strings cannot contain any backticks themselves. Otherwise, they are identical to single-quoted strings.

Double-quoted Strings

For more complex strings, Nushell also offers double-quoted strings. These strings use the " character to surround text. They also support the ability escape characters inside the text using the \ character.

For example, we could write the text hello followed by a new line and then world, using escape characters and a double-quoted string:

> "hello\nworld"
hello
world

Escape characters let you quickly add in a character that would otherwise be hard to type.

Nushell currently supports the following escape characters:

  • \" - double-quote character
  • \' - single-quote character
  • \\ - backslash
  • \/ - forward slash
  • \b - backspace
  • \f - formfeed
  • \r - carriage return
  • \n - newline (line feed)
  • \t - tab
  • \uXXXX - a unicode character (replace XXXX with the number of the unicode character)

Bare strings

Like other shell languages (but unlike most other programming languages) strings consisting of a single 'word' can also be written without any quotes:

> print hello
hello
> [hello] | describe
list<string>

But be careful - if you use a bare word plainly on the command line (that is, not inside a data structure or used as a command parameter) or inside round brackets ( ), it will be interpreted as an external command:

> hello
Error: nu::shell::external_command

  × External command failed
   ╭─[entry #5:1:1]
 1 │ hello
   · ──┬──
   ·   ╰── executable was not found
   ╰────
  help: program not found

Also, many bare words have special meaning in nu, and so will not be interpreted as a string:

> true | describe
bool
> [true] | describe
list<bool>
> [trueX] | describe
list<string>
> trueX | describe
Error: nu::shell::external_command

  × External command failed
   ╭─[entry #5:1:1]
 1 │ trueX | describe
   · ──┬──
   ·   ╰── executable was not found
   ╰────
  help: program not found

So, while bare strings are useful for informal command line usage, when programming more formally in nu, you should generally use quotes.

Strings as external commands

You can place the ^ sigil in front of any string (including a variable) to have Nushell execute the string as if it was an external command:

^'C:\Program Files\exiftool.exe'

> let foo = 'C:\Program Files\exiftool.exe'
> ^$foo

You can also use the run-external command for this purpose, which provides additional flags and options.

String interpolation

More complex string use cases also need a new form of string: string interpolation. This is a way of building text from both raw text and the result of running expressions. String interpolation combines the results together, giving you a new string.

String interpolation uses $" " and $' ' as ways to wrap interpolated text.

For example, let's say we have a variable called $name and we want to greet the name of the person contained in this variable:

> let name = "Alice"
> $"greetings, ($name)"
greetings, Alice

By wrapping expressions in (), we can run them to completion and use the results to help build the string.

String interpolation has both a single-quoted, $' ', and a double-quoted, $" ", form. These correspond to the single-quoted and double-quoted strings: single-quoted string interpolation doesn't support escape characters while double-quoted string interpolation does.

As of version 0.61, interpolated strings support escaping parentheses, so that the ( and ) characters may be used in a string without Nushell trying to evaluate what appears between them:

> $"2 + 2 is (2 + 2) \(you guessed it!)"
2 + 2 is 4 (you guessed it!)

Splitting strings

The split row command creates a list from a string based on a delimiter.

> "red,green,blue" | split row ","
╭───┬───────╮
│ 0 │ red   │
│ 1 │ green │
│ 2 │ blue  │
╰───┴───────╯

The split column command will create a table from a string based on a delimiter. This applies generic column names to the table.

> "red,green,blue" | split column ","
╭───┬─────────┬─────────┬─────────╮
│ # │ column1 │ column2 │ column3 │
├───┼─────────┼─────────┼─────────┤
│ 0 │ red     │ green   │ blue    │
╰───┴─────────┴─────────┴─────────╯

Finally, the split chars command will split a string into a list of characters.

> 'aeiou' | split chars
╭───┬───╮
│ 0 │ a │
│ 1 │ e │
│ 2 │ i │
│ 3 │ o │
│ 4 │ u │
╰───┴───╯

The str command

Many string functions are subcommands of the str command. You can get a full list using help str.

For example, you can look if a string contains a particular substring using str contains:

> "hello world" | str contains "o wo"
true

(You might also prefer, for brevity, the =~ operator (described below).)

Trimming strings

You can trim the sides of a string with the str trim command. By default, the str trim commands trims whitespace from both sides of the string. For example:

> '       My   string   ' | str trim
My   string

You can specify on which side the trimming occurs with the --right and --left options. (-r and -l being the short-form options respectively)

To trim a specific character, use --char <Character> or -c <Character> to specify the character to trim.

Here's an example of all the options in action:

> '=== Nu shell ===' | str trim -r -c '='
=== Nu shell

Substrings

Substrings are slices of a string. They have a startpoint and an endpoint. Here's an example of using a substring:

> 'Hello World!' | str index-of 'o'
4
> 'Hello World!' | str index-of 'r'
8
> 'Hello World!' | str substring '4,8'
o Wo

String padding

With the str lpad and str rpad commands you can add padding to a string. Padding adds characters to string until it's a certain length. For example:

> '1234' | str lpad -l 10 -c '0'
0000001234
> '1234' | str rpad -l 10 -c '0' | str length
10

Reversing strings

This can be done easily with the str reverse command.

> 'Nushell' | str reverse
llehsuN
> ['Nushell' 'is' 'cool'] | str reverse
╭───┬─────────╮
│ 0 │ llehsuN │
│ 1 │ si      │
│ 2 │ looc    │
╰───┴─────────╯

String parsing

With the parse command you can parse a string into columns. For example:

> 'Nushell 0.80' | parse '{shell} {version}'
╭───┬─────────┬─────────╮
│ # │  shell  │ version │
├───┼─────────┼─────────┤
│ 0 │ Nushell │ 0.80    │
╰───┴─────────┴─────────╯
> 'where all data is structured!' | parse --regex '(?P<subject>\w*\s?\w+) is (?P<adjective>\w+)'
╭───┬──────────┬────────────╮
│ # │ subject  │ adjective  │
├───┼──────────┼────────────┤
│ 0 │ all data │ structured │
╰───┴──────────┴────────────╯

If a string is known to contain comma-separated, tab-separated or multi-space-separated data, you can use from csv, from tsv or from ssv:

> "acronym,long\nAPL,A Programming Language" | from csv
╭───┬─────────┬────────────────────────╮
│ # │ acronym │          long          │
├───┼─────────┼────────────────────────┤
│ 0 │ APL     │ A Programming Language │
╰───┴─────────┴────────────────────────╯
> "name  duration\nonestop.mid  4:06" | from ssv
╭───┬─────────────┬──────────╮
│ # │    name     │ duration │
├───┼─────────────┼──────────┤
│ 0 │ onestop.mid │ 4:06     │
╰───┴─────────────┴──────────╯
> "rank\tsuit\nJack\tSpades\nAce\tClubs" | from tsv
╭───┬──────┬────────╮
│ # │ rank │  suit  │
├───┼──────┼────────┤
│ 0 │ Jack │ Spades │
│ 1 │ Ace  │ Clubs  │
╰───┴──────┴────────╯

String comparison

In addition to the standard == and != operators, a few operators exist for specifically comparing strings to one another.

Those familiar with Bash and Perl will recognise the regex comparison operators:

> 'APL' =~ '^\w{0,3}$'
true
> 'FORTRAN' !~ '^\w{0,3}$'
true

Two other operators exist for simpler comparisons:

> 'JavaScript' starts-with 'Java'
true
> 'OCaml' ends-with 'Caml'
true

Converting strings

There are multiple ways to convert strings to and from other types.

To string

  1. Using into string. e.g. 123 | into string
  2. Using string interpolation. e.g. $'(123)'
  3. Using build-string. e.g. build-string (123)

From string

  1. Using into <type>. e.g. '123' | into int

Coloring strings

You can color strings with the ansi command. For example:

> $'(ansi purple_bold)This text is a bold purple!(ansi reset)'

ansi purple_bold makes the text a bold purple ansi reset resets the coloring to the default. (Tip: You should always end colored strings with ansi reset)