W3cubDocs

/Nushell

reduce for filters

Aggregate a list to a single value using an accumulator closure.

Signature

> reduce {flags} (closure)

Flags

  • --fold, -f {any}: reduce with initial value

Parameters

  • closure: reducing function

Input/output types:

input output
list<any> any
range any
table any

Examples

Sum values of a list (same as 'math sum')

> [ 1234 ] |reduce {|it, acc| $it+$acc }
10

Sum values of a list, plus their indexes

> [ 876 ] |enumerate|reduce-f0 {|it, acc| $acc+$it.item+$it.index }
24

Sum values with a starting value (fold)

> [ 1234 ] |reduce-f10 {|it, acc| $acc+$it }
20

Replace selected characters in a string with 'X'

> [ iot ] |reduce-f"Arthur, King of the Britons" {|it, acc| $acc|str replace-a$it"X" }
ArXhur, KXngXfXheBrXXXns

Add ascending numbers to each of the filenames, and join with semicolons.

> ['foo.gz', 'bar.gz', 'baz.gz'] |enumerate|reduce-f'' {|strall| $"($all)(if$str.index!=0 {'; '})($str.index+1)-($str.item)" }
1-foo.gz;2-bar.gz;3-baz.gz

Concatenate a string with itself, using a range to determine the number of times.

>lets="Str";0..2|reduce-f'' {|it, acc| $acc+$s}
StrStrStr

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