【问题标题】:Bash check is file with variable name inside loop existsBash 检查是否存在循环内具有变量名的文件
【发布时间】:2015-07-27 19:01:45
【问题描述】:

我想检查一个文件是否存在。当然这在很多地方都有解释。现在我在一个循环中:

for ((l=0;l<5;l+=1));

do

if -a FILENAMEl #FILENAME contains l!!!!!!!!!

then "FILENAMEl exists"

else

do

.............

fi

done

有什么想法吗?

非常感谢!!!

【问题讨论】:

  • 你到底想在这里做什么? -a 是什么?您是否尝试构建带有后缀的文件名并检查它(如file1file2 等)?
  • 您是要检查一个名为 exactly 的文件,还是按数字或包含该数字作为子字符串?
  • 此外,“子字符串”方法可能无法如您所愿。毕竟,“file102”包含“2”。除了“102”之外,您是否希望“file102”为“2”返回 true?
  • 一个更好的问题会给出你的文件名的例子(如果不是规范)。
  • (另外,-a 不是 bash 命令;它是test 命令的一个可能参数,也可以写成[,但它本身什么也不做) .

标签: bash loops conditional-statements


【解决方案1】:

主要问题是您将变量名l 的语法与文件名的语法混合在一起。如果您希望将它们一起使用,以形成带有变量的文件名的一部分,您需要语法中断(由 "$" 引起),或使用大括号 ({})。

如果文件名中间有一个变量,那么大括号效果最好。例如:"my_file_${l}_head.txt" 会创建 my_file_1_head.txtmy_file_2_head.txt 等文件。

这是您更正的原始示例:

for ((l=0;l<5;l+=1))
do
    if test -a FILENAME$l 
    then echo "FILENAME$l exists"
    else echo "FILENAME$l doesn't exist"
    fi
done

但是,我不会这样写代码。

我只是以你的例子为例,尽可能少地改变它,向你展示本质的区别。

这是另一种编写方式,使用更 DRY(不要重复自己)的方法:

for l in {1..5}; do
  file="filename$l"
  if [[ -a "$file" ]]; then
    echo "$file exists"
  else
    echo "$file does not exist"
  fi
done

如果你想要更多的极简主义,这里还有另一种方法:

for l in {1..5}; do f="filename$l"
  [[ -a "$f" ]] && echo "$f exists" || echo "$f does not exist"
done

现在,如果您需要做的不仅仅是打印状态,使用函数调用来使额外的工作模块化效果很好:

for l in {1..5} ; do f="$filename$l"
  [[ -a "$f" ] && process_file $f || non_existant_file $f
done

然后,在其他地方,您应该同时定义 process_filenon_existant_file

process_file() {
   local file="$1"
   # do whatever is needed for an existing file
}

non_existant_file() {
   local file="$1"
   # do whatever is needed for a non-existant file
}

【讨论】:

    【解决方案2】:

    假设您正在尝试查找文件名格式为 file1.csv、file2.csv 等的文件...

     for i in {1..5}; 
          do f="file$i.csv"; 
             if test -e $f; 
                then echo "$f exists"; 
                else echo "$f does not exist"; 
             fi 
          done
    

    也许你需要的只是一个find

     find . -name "file?.csv" -size +10k
    

    您可以将文件名限制为后缀 1..5 并对查找结果执行操作(检查 find 的 -exec 或更一般的 xargs,如下所示)。

    find . -name "file[1-5].csv" -size +10c | xargs head -1
    

    【讨论】:

    • 啊,非常感谢!有用!还有一个问题:如何插入文件(它是 .txt)有条目或大于 10kB 的附加条件?
    • 如果是文本文件,最简单的方法是使用size = $(wc -c &lt; filename)
    • 我找到了 $f -ge 9,其中 f 是文件名,9 是 9kB。所以在这里我检查文件是否大于或等于 9kB。但是如果我想检查两个条件(文件存在并且大于...) if [[ -e $f ]] && [[$f -ge 9]] ?
    猜你喜欢
    • 2011-12-19
    • 2020-08-09
    • 1970-01-01
    • 2021-01-10
    • 2011-12-25
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2013-10-22
    相关资源
    最近更新 更多