Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can i specify the sort rule when sort an table #12605

Open
malongshuai opened this issue Apr 21, 2024 · 1 comment
Open

Can i specify the sort rule when sort an table #12605

malongshuai opened this issue Apr 21, 2024 · 1 comment
Labels
question the issue author asks something

Comments

@malongshuai
Copy link

malongshuai commented Apr 21, 2024

Question

for example, i want to sort the result of ls command by the filename length.

~> ls
╭───┬─────────────────────┬──────┬─────────┬──────────────╮
│ # │        name         │ type │  size   │   modified   │
├───┼─────────────────────┼──────┼─────────┼──────────────┤
│ 0 │ dump.rdb            │ file │   975 B │ 3 weeks ago  │
│ 1 │ redis-stable        │ dir  │ 4.0 KiB │ 3 months ago │
│ 2 │ redis-stable.tar.gz │ file │ 3.3 MiB │ 3 months ago │
╰───┴─────────────────────┴──────┴─────────┴──────────────╯

i checked the document: sort-by(https://www.nushell.sh/commands/docs/sort-by.html), i think it can accept a closure to sort by any rule. like this:

ls | sort-by {|row| $row.name | length}

Additional context and details

No response

@malongshuai malongshuai added the question the issue author asks something label Apr 21, 2024
@woosaaahh
Copy link
Contributor

Hi !

The only parameters that sort-by accept are the column names.

It's not mentioned in the documentation but those parameters must be string.
See the line here https://github.com/nushell/nushell/blob/main/crates/nu-command/src/filters/sort_by.rs#L81
The let columns: Vec<String> part can be understood as "columns will be a vector (kind of array) of strings".

To solve your problem, you can use a temporary column and sort-by it.

ls | insert name_len { get name | str length } | sort-by name_len | reject name_len
> [[name]; [a] [bcd] [ef]]
╭───┬──────╮
 # │ name │
├───┼──────┤
 0  a    
 1  bcd  
 2  ef   
╰───┴──────╯
> [[name]; [a] [bcd] [ef]]
::: | insert name_len { get name | str length }
::: | sort-by name_len
::: | reject name_len
╭───┬──────╮
 # │ name │
├───┼──────┤
 0  a    
 1  ef   
 2  bcd  
╰───┴──────╯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question the issue author asks something
Projects
None yet
Development

No branches or pull requests

2 participants