首页 > 解决方案 > 如果在 bash 中包含特定文件名,则仅列出目录

问题描述

大家好,我需要 bash 命令方面的帮助。

这是交易:

我有几个目录:

path1/A/path2/
 file1
 file2
path1/B/path2/
 file1
path1/C/path2/
 file1
 file2
path1/D/path2/
 file1
 file2

和一个/path_to_this_file/file.txt

A
B
C
D

我使用的是:

cat /path_to_this_file/file.txt | while read line; do ls path1/$line/path2/

然后我可以列出路径中的所有内容,但我只想为path2那些没有file2进入他们的目录的 ls 做一个 ls 。

此处仅path1/B/path2/应列出

有人有代码吗?

标签: linuxbashls

解决方案


在您的代码中添加了 if 语句:

cat /path_to_this_file/file.txt |
    while read line
    do
        if [ ! -f "path1/$line/path2/file2" ]; then
            ls path1/$line/path2/
        fi
    done

或者:

xargs -I {} bash -c "[ ! -f "path1/{}/path2/file2" ] && ls path1/{}/path2" < /path_to_this_file/file.txt

推荐阅读