【问题标题】:Sorting an array of pathnames (strings) [Bash]对路径名(字符串)数组进行排序 [Bash]
【发布时间】:2016-09-20 05:23:15
【问题描述】:

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

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

【问题讨论】:

  • $input 不是数组,而是字符串。另外,${a[@]} 是如何填充的?
  • @choroba Ops,我只是从另一个 SO 问题复制并粘贴,因为我没有代码了。
  • input 正好包含字符串/foo/bar/*;赋值语句中不会发生路径名扩展。

标签: arrays linux bash shell sorting


【解决方案1】:

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

input=/foo/bar/*

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

你想要这个:

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

我没有时间解释它。我稍后会回来。

【讨论】:

  • 是的,大概就是这样。我对 Bash 很陌生,考虑到 C++、Lua、Python 中的几乎所有列表类型结构......(VB.NET - 但我不想谈论那个)是一个数组,我在这里自动假设相同.
  • bash 的数据结构很差,因为它不是为处理数据而设计的;它是一种便于运行其他程序的胶水语言。
【解决方案2】:

您可以将sort -rprintf 一起使用,其中input 包含glob 字符串以匹配您的文件名:

sort -r <(printf "%s\n" $input)

【讨论】:

  • 同意,非常聪明,紧凑且直观。谢谢!
  • 但请注意:如果 input 的值包含任何空格,它也不起作用。
  • 是的,我知道带有空格的文件,但根据 OP,文件名为 /foo/bar/file1 /foo/bar/file2 /foo/bar/file3。此外,我还使用带空格的文件名对此进行了测试。我认为带有换行符的文件名会有问题。
  • 是的,我不打算在路径名中使用空格,它是一个带有(由我)设置的文件名的静态目录 - 我只是想让它有点模块化。
【解决方案3】:

这行得通:

input=`foo/bar/*`
output=`for l in $input ; do echo $l ; done | sort -r`

【讨论】:

    猜你喜欢
    • 2016-07-18
    • 2017-03-04
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多