Search

Dark theme | Light theme

February 27, 2025

Nushell Niceties: Converting Strings To Kebab Case

Nushell has a lot of commands to work with strings. The str kebab-case command can be used to convert a string to kebab case. Kebab-case is a string that contains only lowercase letters and words are separated by hyphens.

In the following example you can see how to use the str kebab-case command for a string value:

# Add assertion support.
use std/assert

# Different examples of string types that are transformed to kebab-case.
assert equal ('stringInCamelCase' | str kebab-case) 'string-in-camel-case'
assert equal ('string_with_underscores' | str kebab-case) 'string-with-underscores'
assert equal ('StringInPascalCase' | str kebab-case) 'string-in-pascal-case'
assert equal ('string with spaces' | str kebab-case) 'string-with-spaces'
assert equal ('STRING-WITH-UPCASE' | str kebab-case) 'string-with-upcase'

# Special characters are removed.
assert equal ('Nushell rocks!' | str kebab-case) 'nushell-rocks'

The str kebab-case command accepts as extra argument one or more names of keys in a record. The values of these keys are transformed to kebab-case as you can see in the following example:

use std/assert

# The str kebab-case command accepts names of keys to
# transform the values to kebab-case in a record.
let user = {
    name: 'Hubert Klein Ikkink',
    alias: 'MrHaki'
} | str kebab-case name alias

assert equal $user {
    name: 'hubert-klein-ikkink',
    alias: 'mr-haki'
}

The str kebab-case command can be applied to lists to transform each element to kebab-case:

use std/assert

# The str kebab-case command can be applied to lists
# to transform each element to kebab-case.
let shells = ['Nushell' 'PowerShell'] | str kebab-case
assert equal $shells ['nushell' 'power-shell']

Finally the str kebab-case command can be used to transform the values in a column to kebab-case. The names of the columns must be passed as extra arguments to the str kebab-case command:

use std/assert

# The str kebab-case command also accepts names of columns for a table.
# The values in the column are transformed to kebab-case.
let users = [
    [name alias];
    ['Hubert Klein Ikkink' 'MrHaki']
] | str kebab-case alias

# Values in the alias column are transformed into kebab-case.
assert equal $users.alias ['mr-haki']
# Values in the name column are not changed.
assert equal $users.name ['Hubert Klein Ikkink']
# Assertion for complete table.
assert equal $users [[name alias]; ['Hubert Klein Ikkink' 'mr-haki']]

Written with Nushell 0.102.0.