【问题标题】:wbash -- checking if directory has folder and corresponding filewbash -- 检查目录是否有文件夹和对应的文件
【发布时间】:2017-11-04 20:27:04
【问题描述】:

我是 bash 的新手,我正在尝试查看我的目录是否包含与其对应的 txt 文件的文件夹。并不是所有的文件夹都有对应的txt文件,而且目录里面有很多文件夹和txt文件,所以想自动化一下。

示例目录:

a_1/
a_1.txt
b_1/
b_1.txt
c_1/
c_1.txt
d_1/

我了解如何分别检查目录中是否存在文件或文件夹。但是我无法检查文件夹中是否存在相应的 txt 文件。

我想要一些可以打印出文件夹的东西,但文件不存在。 从上面的例子中,它会打印有对应文件夹的文件:folder a_1/ and a_1.txt both exist,但没有对应的txt文件:d_1/ exist but txt file doesn't.

这是我目前拥有的,但它似乎不起作用。 :(

#!/bin/bash
for x in *; do
    if [[ -d  "$DIRECTORY" ]] && [[ -f ${f%.txt} ]]; then
        echo -n "$x ${x%%.dir}.txt are both present ";
    else
        echo "directory '$DIRECTORY' existed but didn't find txt file"

【问题讨论】:

  • 对于初学者:你永远不会关闭for循环;在循环中,您使用三个变量:$DIRECTORY$f$x,但实际上只定义了 $x(假设这是整个代码)。
  • @MirosławZalewski 感谢您指出这一点! :)

标签: linux bash


【解决方案1】:

根据您的规范,脚本已更正:

#!/bin/bash

for x in *; do
    if [[ -d "$x" ]]; then
        if [[ -f $x.txt ]]; then
            echo "$x and $x.txt are both present "
        else
            echo "Directory '$x' exists but $x.txt doesn't"
        fi
    fi
done

【讨论】:

    【解决方案2】:

    只是对上面回复的评论,双[[和]]不是必需的。此外,您可以使用句点来表示当前的工作目录(顺便说一下,这个 bash 技巧也适用于命令行):

    for x in .; do
        if [ -d ${x} ]; then
            ...
        fi
    done
    

    您还可以从命令行指定路径:

    ./myprog.sh /Volumes/myflashdrive/filedir

    path=${1}
    
    for x in ${path}; do
        if [ -d ${x} ]; then
            ...
        fi
    done
    

    【讨论】:

      猜你喜欢
      • 2011-02-12
      • 2014-05-10
      • 2022-11-01
      • 2015-11-11
      • 2012-07-30
      • 2023-03-25
      • 2022-01-23
      • 2010-11-08
      • 2016-05-20
      相关资源
      最近更新 更多