我们可以使用find关键字找到目标文件的完整绝对路径。在我的例子中,我需要所有直接下一个目录到我指定的位置的列表,它可以引导我找到名为foo.log的程序日志文件。
例如,其中一些路径可能是:
given-location/alpha/beta/gamma/foo.log
given-location/apple/banana/foo.log对于上述情况,我需要一个列表/数组/向量(类似于['alpha', 'apple'] )作为我的结果,因为它包含了到达目标文件的所有可能的下一个文件夹。
我对Linux工具很陌生。我知道,我总是可以创造一个蛮力的解决方案,因为我有绝对路径以及给定的路径,但任何优化/更好的解决方案或任何提示/想法在正确的方向就可以了!
我不想要第一个不同的文件夹,只是直接文件夹到给定的位置。
我的蛮力方法:
result={}
for all the Absolute-path which can reach foo.log:
Suffix-path = (Absolute-path - given-path)
Append the Suffix-path[0] to result发布于 2021-02-12 06:22:41
%P格式指令将直接在起始点之后为您提供路径:
find given-location/ -type f \
-name 'foo.log' -printf %P\\n | cut -f1 -d /可以使用find操作符将来自+=的输出附加到数组中:
a=(); a+=( \
$(find given-location/ -type f \
-name 'foo.log' -printf %P\\n | cut -f1 -d / \
) \
); echo "${a[@]}"下一个示例使用globstar **/;匹配零或多个子目录。
#!/bin/bash
shopt -s globstar nullglob
a=()
for b in given-location/**/foo.log; do
readarray -t -d / -s 1 -n 1 -O ${#a[@]} a <<< "$b"
done
echo "${a[@]}"将使用-O的开始索引移到数组的末尾,就可以追加新的值。
-t移除尾随的剥离物-d Delim用于终止每个输入行,而不是换行符。-s丢弃读取的第一行计数。-n。-O开始在索引原点为数组赋值。发布于 2021-02-12 06:02:39
使用awk获取字符串的第二个字段:
$ echo 'given-location/alpha/beta/gamma/foo.log' | awk -F/ '{print $2}'
alpha
awk command options used
-F/ : specify '/' as fields separator char
$2 : second fieldhttps://askubuntu.com/questions/1315752
复制相似问题