如果Linux子目录中的文件不存在,则命令检索父目录名称

时间:2019-03-14 07:07:46

标签: linux

19.08子文件夹中没有出现final.txt时,将目录名称获取为输出(trans)。主父目录名称(19.02,19.04,19.06)不断变化。但是子文件夹名称(base and trans)始终相同,final.txt始终仅在trans文件夹下可用。

当trans文件夹下的final.txt不可用时,应该在Linux / shell中将19.08作为输出返回吗?

请对此提出建议

     |--Project
        |-- 19.02
        |   |-- base
        |   |-- trans
                -- final.txt
        |-- 19.04
        |   |-- base
        |   |-- trans
                -- final.txt
        |-- 19.06
        |   |-- base
        |   |-- trans
                -- final.txt
        |-- 19.08
            |-- base
            |-- trans

提前谢谢!

2 个答案:

答案 0 :(得分:2)

此脚本将打印Project中所有不包含文件trans/final.txt的目录名称。

# The trailing / makes sure we loop over directories only
for DIR in Project/*/
do
     # additional condition "if [ -d "$DIR" ] &&..." is not necessary because of the trailing / above
     if [ ! -f "${DIR}/trans/final.txt" ]
     then
         # basename removes both the trailing / and the parent dir
         basename "$DIR"
     fi
done

答案 1 :(得分:1)

基于this thread的纯查找解决方案:

find . -mindepth 2 -maxdepth 2 -type d '!' -exec sh -c 'test -e "$1"/trans/final.txt' -- {} ';' -print | 
# remove the leading Project from path
xargs -n1 basename
  1. 查找完全向下两级的目录
  2. 对于每个条目,执行test -e <entry>/trans/final.txt-即。检查final.txt是否存在
  3. 如果不存在'!',则-print路径。
  4. | xargs -n1 basename用于将./Project/19.08转换为19.08

我第一个使用comm并创建列表的解决方案,并在代码中添加了注释:

# Create an MCVE
mkdir -p Project/19.0{2,4,6,8}/{base,trans}
touch Project/19.0{2,4,6}/trans/final.txt

# Extract only unique lines from the first list
# So the folders which do not have final.txt in them
comm -23 <(
    # Create a list of all Project/*/ folders
    find . -mindepth 2 -maxdepth 2 |
    sort
) <(
    # Create a list of all Project/*/*/final.txt files
    find . -mindepth 4 -maxdepth 4 -name final.txt -type f |
    # Extract only Project/*/ part, so twice dirname
    xargs -n1 dirname | xargs -n1 dirname |
    sort
) | 
# Remove the leading 'Project' name
xargs -n1 basename