linux - 仅列出文件的公共(public)父目录

标签 linux bash shell

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

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

在上面的例子中,我只想要公共(public)父目录,在上面的例子中是“/home/nicool/Desktop”。如何使用 bash 来实现?请帮助找到此类问题的通用解决方案。

最佳答案

此脚本在每次迭代中读取行并存储公共(public)前缀:

# 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: http://stackoverflow.com/a/17841619/416224
    local IFS="$1"
    shift
    echo "$*"
}

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

例子:

$ ./x.sh <<eof
/home/nicool/Desktop1/file1.txt
/home/nicool/Desktop2/dir1/file1.txt
/home/nicool/Desktop3/dir1/dir2/file1.txt
eof
/home/nicool

关于linux - 仅列出文件的公共(public)父目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814845/

相关文章:

c - 同一目标模块中的过程调用是否需要在链接阶段重定位

用于 SSH SOCKS 绑定(bind)(动态端口转发)的 Java 库?

linux - 从某一行开始对文件进行排序

c - mq_send 中的发送结构

linux - 从一个文件中读取行范围并在另一个文件中找到该范围内的最大值

linux - 如何在bash中将字符串替换为 "decdump"?

javascript - 将 BASH 的日期格式转换为 JavaScript 的日期格式

shell - 在命令所在的同一行设置变量

c++ - 如何在 C++ 中将所有输入 (cin) 记录到文件中

linux - csv 删除一列中具有重复值的所有行