如果在bash中包含特定文件名,则仅列出目录

问题描述 投票:0回答:3

大家好,我需要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/

然后我可以列出路径中的所有内容,但我只想为目录中没有path2file2做ls。

这里只列出path1/B/path2/

有人为此提供代码吗?

linux bash ls
3个回答
1
投票

在代码中添加了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

1
投票

这将完成工作

while read line; do
    ls "path1/$line/path2/file2" &> /dev/null || ls "path1/$line/path2"
done < /path_to_this_file/file.txt

0
投票

仅使用mapfile akareadarraybash4+for loop

#!/usr/bin/env bash

mapfile -t var < path_to_this_file/file.txt

for i in "${var[@]}"; do
  if [[ ! -e path1/$i/path2/file2 ]]; then
    ls "path1/$i/path2/"
  fi
done

以上代码中的ls

 ls "path1/$i/path2/" 

输出是

file1

如果只打印路径,则将ls "path1/$i/path2/"更改为

echo "path1/$i/path2/" 

输出是

path1/B/path2/

如果要同时打印PATH和文件使用情况

echo "path1/$i/path2/"*

输出是

path1/B/path2/file1
© www.soinside.com 2019 - 2024. All rights reserved.