linux – 仅列出文件的公共父目录

前端之家收集整理的这篇文章主要介绍了linux – 仅列出文件的公共父目录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在搜索一个文件,比如“file1.txt”,并且find命令的输出如下所示.

/home/nicool/Desktop/file1.txt
/home/nicool/Desktop/dir1/file1.txt
/home/nicool/Desktop/dir1/dir2/file1.txt

在上面的例子中我只想要共同的父目录,在上面的例子中是“/ home / nicool / Desktop”.如何使用bash实现?请帮助找到这种问题的一般解决方案.

最佳答案
此脚本读取行并在每次迭代中存储公共前缀:

# read a line into the variable "prefix",split at slashes
IFS=/ read -a prefix

# while there are more lines,one after another read them into "next",# also split at slashes
while IFS=/ read -a next; do
    new_prefix=()

    # for all indexes in prefix
    for ((i=0; i < "${#prefix[@]}"; ++i)); do
        # if the word in the new line matches the old one
        if [[ "${prefix[i]}" == "${next[i]}" ]]; then
            # then append to the new prefix
            new_prefix+=("${prefix[i]}")
        else
            # otherwise break out of the loop
            break
        fi
    done

    prefix=("${new_prefix[@]}")
done

# join an array
function join {
    # copied from: https://stackoverflow.com/a/17841619/416224
    local IFS="$1"
    shift
    echo "$*"
}

# join the common prefix array using slashes
join / "${prefix[@]}"

例:

$./x.sh <
原文链接:https://www.f2er.com/linux/440020.html

猜你在找的Linux相关文章