arrays - 对路径名数组(字符串)进行排序 [Bash]

标签 arrays linux bash shell sorting

我已经看到太多重复的内容,但没有一个答案代码或提示对我有帮助,所以我很困惑。

input=/foo/bar/*;
#Contains something along the lines of 
#/foo/bar/file1 /foo/bar/file2 /foo/bar/file3
#And I simply need
#/foo/bar/file3 /foo/bar/file2 /foo/bar/file1

output=($(for l in ${input[@]}; do echo $l; done | sort));
#Doesn't work, returns only the last entry from input

output=$(sort -nr ${input});
#Works, returns everything correctly reversed, but outputs the file contents and not the pathnames;
output=($(sort -nr ${input}));
#Outputs only the last entry and also its contents and not the pathname;

我尝试了更多选项,但我不会用它们填满整个页面,你懂的。

重复项:(没有一个对我有帮助)

How can I sort the string array in linux bash shell?

How to sort an array in BASH

custom sort bash array

Sorting bash arguments alphabetically

最佳答案

你对什么是 bash 中的数组感到困惑:这并没有声明数组:

input=/foo/bar/*

$input 只是字符串 "/foo/bar/*" -- 文件列表不会扩展,直到你执行类似 for我在 ${input[@]} 中,其中“数组”扩展未被引用。

你想要这个:

input=( /foo/bar/* )
mapfile -t output < <(printf "%s\n" "${input[@]}" | sort -nr)

没时间解释了。我稍后回来。

关于arrays - 对路径名数组(字符串)进行排序 [Bash],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39582148/

相关文章:

php - Golang 用字符串中的数组元素替换数组元素

linux - apache 错误 - 403 禁止在虚拟主机上通过 nginx 反向代理

bash - Matlab parfor 使用的内核数少于分配的内核数

mysql - BASH:SSH 进入服务器,查询 MYSQL 有趣的东西

javascript - 两个对象数组,需要根据另一个对一个数组进行排序

c++ - 访问二维数组时读取冲突

linux - iptables 最近模块 --set 选项

bash - 我可以删除目录,然后在单个命令中创建目录吗?

ios - 无法将类型 '[String]' 的值分配给类型 'String?'

c - 如何让所有人都可以使用我的 API?