我将 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/