Search

Dark theme | Light theme

March 11, 2025

Nushell Niceties: Trimming Strings

Nushell has some powerful commands to work with strings. The str trim command can be used to trim whitespace from a string. By default whitespace from the beginning and end of a string is removed. To only remove whitespace from the beginning of the string you can use the --left argument (or the shorter option -l). For removing whitespace from the end of the string you can use the option --right or the shorter option -r. To trim a string based on another character you can use the option --char or the shorter option -c followed by the character to trim.

In the following example you can see how the str trim command can be used to remove whitespace:

use std/assert

# str trim removes whitespace from the beginning and end of the string
assert equal (' mrhaki ' | str trim) 'mrhaki'

# Use --left or -l to only remove whitespace from the left.
assert equal (' mrhaki ' | str trim --left) 'mrhaki '

# Use --right or -r to only remove whitespace from the right.
assert equal (' mrhaki ' | str trim --right) ' mrhaki'

# With double quoted strings sr trim removes not
# only spaces, but also other characters like \t and \n.
assert equal ("\tmrhaki\n" | str trim) 'mrhaki'
assert equal ("\t mrhaki \n" | str trim) 'mrhaki'

You can use the argument --char or -c to specify another character to use for trimming:

use std/assert

# The str trim command with the --char or -c argument
# to specify a character to trim.
assert equal ('**mrhaki**' | str trim --char '*') 'mrhaki'
assert equal ('* mrhaki *' | str trim -c '*') ' mrhaki '

You can specify the name of keys of a record to trim the values of those keys:

use std/assert

# The str trim command accepts names of keys to
# trim the values of those keys in a record.
let user = {
    name: 'Hubert Klein Ikkink ',
    alias: ' mrhaki '
} | str trim name alias

assert equal $user {
    name: 'Hubert Klein Ikkink',
    alias: 'mrhaki'
}

The str trim command can be applied to lists to trim each element as you can see in the next example:

use std/assert

# The str trim command can be applied to lists
# to trim each element.
let shells = [' NuShell', 'Powershell '] | str trim
assert equal $shells ['NuShell', 'Powershell']

Finally the str trim command can be used to trim the values in one or more columns in a table:

use std/assert

# The str trim command also accepts names of columns for a table.
# The values in the column are trimmed.
let users = [
    [name alias];
    ['Hubert Klein Ikkink ' 'mrhaki ']
] | str trim --right alias

# Name column is not transformed.
assert equal $users.0.name 'Hubert Klein Ikkink '
# Alias column is transformed.
assert equal $users.0.alias 'mrhaki'

Written with Nushell 0.102.0.