×

[Short Tip] Processing line by line in a loop in Nushell – /home/liquidat

[Short Tip] Processing line by line in a loop in Nushell – /home/liquidat


For a test I recently had to process a plain list of items that was outputted by a program. In Bash, the usual way to do so is:

while read -r line; do COMMAND $line; done

But how could this be done in Nushell? Just using the same command gives an error:

❯ flatpak list|grep system|cut -f 2|while read -r line; do flatpak info $line; done
Error: nu::parser::parse_mismatch

× Parse mismatch during operation.
╭─[entry #2:1:1]
1 │ flatpak list|grep system|cut -f 2|while read -r line; do flatpak info $line; done
· ─┬
· ╰── expected operator
╰────

❯ flatpak list|grep system|cut -f 2|while read line; do flatpak info $line; done
Error: nu::parser::parse_mismatch

× Parse mismatch during operation.
╭─[entry #3:1:1]
1 │ flatpak list|grep system|cut -f 2|while read line; do flatpak info $line; done
· ──┬─
· ╰── expected block, closure or record
╰────

Instead, the trick is to tell Nushell to read the input line by line with lines, and then process each and every item with a sub-function:

flatpak list|grep system|cut -f 2| lines|each { |it| flatpak info ($it) }

This worked flawlessly.



Source link