【问题标题】:Bash - File existence providing incorrect resultsBash - 文件存在提供不正确的结果
【发布时间】:2017-02-22 22:58:11
【问题描述】:

我有一个包含文件列表的文件,我想知道这些文件是否存在。我使用了这个命令:

while read line; do 
    filename="$(echo $line | cut -d';' -f4)"; 
    if [ ! -e "/some/path/$filename" ]; 
    then echo "/some/path/$filename"; 
    fi ; 
done < "../my_list_of_file"

此命令将每个列为不存在的文件返回给我,例如:

/some/path/my_listed_file.jpg

但是当我执行ls /some/path/my_listed_file.jpg 时,我可以看到该文件存在。我的命令有什么问题?

【问题讨论】:

  • 这是最后一个字段吗?我怀疑你的文件有 CRLF 行结尾,因为它是在 Windows 上创建的。
  • 如果filename 是每行的最后一个字段,则这指向my_list_of_file 具有DOS 行结尾。文件名实际上以回车结束。
  • 如果是这个问题,请使用dos2unix 修复文件。
  • 另外,让read 为您拆分线路。 while IFS=$';\r' read -r _ _ _ filename _; do。如果 DOS 行尾是问题,如果你先从文件中删除它们,你可以切换到 IFS=";"
  • my_list_of_file 中的文件名是否没有路径?

标签: bash file-exists


【解决方案1】:

感谢 Barmar 和 chepner,问题出在文件末尾的 CRLF。 这是工作命令:

while IFS=$';\r' read -r _ _ _ filename _; do 
    if [ ! -e "/some/path/$filename" ]; 
    then echo "/some/path/$filename"; 
    fi ; 
done < "../my_list_of_file"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-30
    • 2014-03-27
    • 2021-10-02
    • 2018-04-11
    • 2018-02-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    相关资源
    最近更新 更多