简体   繁体   English

检查是否存在与目录同名的文件

[英]Check if a file exists with the same name as a directory

I'm trying to make a script that will determine whether a '.zip' file exists for each sub-directory. 我正在尝试创建一个脚本来确定每个子目录是否存在'.zip'文件。 For example the directory I'm working in could look like this: 例如,我正在使用的目录可能如下所示:

/folder1
/folder2
/folder3
folder1.zip
folder3.zip

The script would then recognise that a '.zip' of "folder2" does not exist and then do something about it. 然后该脚本将识别出“folder2”的“.zip”不存在,然后对其执行某些操作。

So far I've come up with this (below) to loop through the folders but I'm now stuck trying to convert the directory path into a variable containing the file name. 到目前为止,我已经提出了这个(下面)循环文件夹,但我现在卡住尝试将目录路径转换为包含文件名的变量。 I could then run an if to see whether the '.zip' file exists. 然后我可以运行if来查看'.zip'文件是否存在。

#!/bin/sh

for i in $(ls -d */);
do
    filename= "$i" | rev | cut -c 2- | rev
    filename="$filename.zip"
done
# No need to use ls
for dir in */
do
  # ${var%pattern} removes trailing pattern from a variable
  file="${dir%/}.zip"
  if [ -e "$file" ]
  then
    echo "It exists"
  else
    echo "It's missing"
  fi
done

Capturing command output wasn't necessary here, but your line would have been: 此处不需要捕获命令输出,但您的行应该是:

# For future reference only
filename=$(echo "$i" | rev | cut -c 2- | rev)

You can do it with something like: 你可以这样做:

#!/bin/sh

for name in $(ls -d */); do
    dirname=$(echo "${name}" | rev | cut -c 2- | rev)
    filename="${dirname}.zip"
    if [[ -f ${filename} ]] ; then
        echo ${dirname} has ${filename}
    else
        echo ${dirname} has no ${filename}
    fi
done

which outputs, for your test case: 哪个输出,为您的测试用例:

folder1 has folder1.zip
folder2 has no folder2.zip
folder3 has folder3.zip

You can do it without calling ls and this tends to become important if you do it a lot, but it's probably not a problem in this case. 可以在不调用ls情况下执行此操作,如果您执行此操作,这往往会变得很重要,但在这种情况下可能不是问题。

Be aware I haven't tested this with space-embedded file names, it may need some extra tweaks for that. 请注意,我没有使用空间嵌入文件名对此进行测试,可能需要进行一些额外的调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM