Reputation: 1886
how to redirect some command output to a file in NuShell
?
In zsh/bash we can redirect output of ls
command to a file as below
ls > fileList.txt
how can we do the same in NuShell?
Upvotes: 6
Views: 4286
Reputation: 1732
To update this answer based on more recent Nu (v 0.84 as I write this):
Nushell now has redirection operators: out>
and out+err>
, similar to sh-shells 1>
2>&1
etc. Can be used as follows:
> 10 + 20 out> t.t
> cat t.t
30
Redirection operators compared to save
.
out+err>
(abbreviated o+e>
) can capture both streams to a single file. save f.f --stderr f.f
refuses to save both streams to same file.| save
. They are, er, postfix operators in an expression.save
, the input for redirection operators must be string or converted to string via to json
as suggested above.Upvotes: 4
Reputation: 1886
Below command saved the ls output
in json format and retrieved in exact format.
ls | to json | save -f fileList.json
open fileList.json
use --force
option to overwrite file.
command help save
is your friend on terminal:
> help save 06/06/2023 10:50:48 PM
Save a file.
Search terms: write, write_file, append, redirection, file, io, >, >>
Usage:
> save {flags} <filename>
...more info here...
...more info here...
Examples:
Save a string to foo.txt in the current directory
> 'save me' | save foo.txt
Append a string to the end of foo.txt
> 'append me' | save --append foo.txt
Save a record to foo.json in the current directory
> { a: 1, b: 2 } | save foo.json
Save a running program's stderr to foo.txt
> do -i {} | save foo.txt --stderr foo.txt
Save a running program's stderr to separate file
> do -i {} | save foo.txt --stderr bar.txt
Upvotes: 1
Reputation: 36391
To redirect/save into a file, use the save
command (see the manual).
However, save
takes strings as input, while ls
provides records. You can convert those records into strings by defining how.
One way, if your primary interest lies in saving the looks, is to explicitly render the table as shown in your shell using the table
command (see the manual which even lists ls | table
as one of the examples):
ls | table | save fileList.csv
But if you are more interested in the data conveyed, re-format it into a datatype of your choice using to
(see a list of formats). For example, to re-format it as CSV use to csv
, for HTML use to html
, for JSON use to json
etc. There is also to text
which simply lists all records line by line with their key names prepended. Its manual page even lists ls | to text
as one of the examples.
ls | to csv | save fileList.csv
# or
ls | to html | save fileList.html
# or
ls | to json | save fileList.json
# or
ls | to text | save fileList.txt
# etc.
Upvotes: 5