【问题标题】:list only directory if contain a specific file name in bash如果在 bash 中包含特定文件名,则仅列出目录
【发布时间】:2020-03-20 10:06:27
【问题描述】:

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

然后我可以列出路径中的所有内容,但我只想为没有file2path2 做一个 ls 到他们的目录中..

这里应该只列出path1/B/path2/

有人有代码吗?

【问题讨论】:

    标签: linux bash ls


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      这样就可以了

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

      【讨论】:

        【解决方案3】:

        仅使用 mapfile aka readarray bash4+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
        

        如果您只想打印 PATH,请将 ls "path1/$i/path2/" 更改为

        echo "path1/$i/path2/" 
        

        输出是

        path1/B/path2/
        

        如果你想同时打印 PATH 和文件使用

        echo "path1/$i/path2/"*
        

        输出是

        path1/B/path2/file1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-29
          • 1970-01-01
          • 2018-04-17
          • 1970-01-01
          • 2019-08-24
          • 2014-03-08
          相关资源
          最近更新 更多