【问题标题】:Bash: how to extract longest directory paths from an array?Bash:如何从数组中提取最长的目录路径?
【发布时间】:2020-06-06 20:41:21
【问题描述】:

我将find 命令的输出放入数组中,如下所示:

pathList=($(find /foo/bar/ -type d))

如果数组包含多个等长的最长路径,如何提取数组中找到的最长路径?:

echo ${pathList[@]}
/foo/bar/raw/
/foo/bar/raw/2020/
/foo/bar/raw/2020/02/
/foo/bar/logs/
/foo/bar/logs/2020/
/foo/bar/logs/2020/02/

提取后,我想将/foo/bar/raw/2020/02//foo/bar/logs/2020/02/ 分配给另一个数组。

谢谢

【问题讨论】:

  • wrt I put the output of find command into array like this: - 不要这样做,因为它不健壮,例如当您的目录名称包含空格时,它将失败。请参阅stackoverflow.com/q/23356779/1745001,了解如何使用命令的输出填充数组。另外,定义“最长” - 最多总字符或必须子目录或其他内容?
  • 能否请您确认一下您想要获取的最长路径的定义,我认为您需要按目录级别输出,请在此处确认。
  • @RavinderSingh13,是的,“最长路径”是指目录级别。您的解决方案效果很好,因此我接受它作为答案

标签: arrays bash awk find


【解决方案1】:

请您尝试以下操作。这应该打印最长的数组(可以是多个相同最大长度的数组),您可以将其分配给以后的数组。

echo "${pathList[@]}" |
awk -F'/' '{max=max>NF?max:NF;a[NF]=(a[NF]?a[NF] ORS:"")$0} END{print a[max]}'


我刚刚使用您提供的值创建了一个测试数组,并对其进行了如下测试:

arr1=($(printf '%s\n' "${pathList[@]}" |\
awk -F'/' '{max=max>NF?max:NF;a[NF]=(a[NF]?a[NF] ORS:"")$0} END{print a[max]}'))

当我看到新数组的内容时,它们如下:

echo  "${arr1[@]}"
/foo/bar/raw/2020/02/
/foo/bar/logs/2020/02/

awk代码的解释:添加awk代码的详细解释。

awk -F'/' '                        ##Starting awk program from here and setting field separator as / for all lines.
{
  max=max>NF?max:NF                ##Creating variable max and its checking condition if max is greater than NF then let it be same else  set its value to current NF value.
  a[NF]=(a[NF]?a[NF] ORS:"")$0     ##Creating an array a with index of value of NF and keep appending its value with new line to it.
}
END{                               ##Starting END section of this program.
  print a[max]                     ##Printing value of array a with index of variable max.
}'

【讨论】:

  • 只是一个后续问题 - 我试图循环遍历 arr1 ,它似乎只包含一项而不是两项。您将如何将 arr1 中的这两个目录路径分开,使它们成为两个单独的项目?谢谢。
  • @kamokoba,请你现在检查我的 arr1 答案,让我知道我现在不在我的办公桌上,所以没有测试应该工作,但是,让我知道
  • 它现在可以在添加额外的括号后使用。谢谢,感谢您的宝贵时间!
猜你喜欢
  • 2012-01-03
  • 2011-09-01
  • 2013-09-21
  • 1970-01-01
  • 2012-03-05
  • 2011-09-24
  • 2014-03-07
  • 1970-01-01
相关资源
最近更新 更多