arrays - Bash:如何从数组中提取最长的目录路径?

标签 arrays bash awk find

我将 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/ 分配给另一个数组。

谢谢

最佳答案

您可以尝试关注吗?这应该打印最长的数组(可能是多个相同最大长度的数组),您可以将其分配给稍后的数组。

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.
}'

关于arrays - Bash:如何从数组中提取最长的目录路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60355230/

相关文章:

php - 如何在现有的 foreach 中进行 php 循环以连接 SQL 表

c++ - 对字符串指针数组进行排序

linux - Bash:将当前路径剪切到某个文件夹

linux - 来自键盘的变量等于bash

bash - awk中单引号和双引号的区别

javascript - 如何将用户输入的输入保存为 React 中的数组状态

javascript - 当名称未知时查找并存储 JSON 嵌套数组

bash - AWS 弹性 Beanstalk : the command eb list shows no environments

bash - 使用 awk 为患者识别疾病

bash - 使用控制语句在 AWK (GNU) 中动态传递月份名称