Shell:更改格式时检查文件是否存在

问题描述 投票:0回答:1

我正在尝试编写一个脚本,在运行时,将目录中的所有.htm文件重命名为.html,用于服务器。没问题!

for file in *.htm ; do mv $file `echo $file | sed 's/\(.*\.\)htm/\1html/'` ; done

但是,如果已经有一个.html等效的文件,它应该打印出“$ file.html已经转换 - 联系管理员”并退出状态1

我尝试过使用-mv并存在,但没有雪茄。任何帮助赞赏。

bash shell unix exists
1个回答
1
投票

您应首先检查文件,然后尝试通过移动重命名。

这样的事情应该足够了:

for file in *.htm; do
  [ -f "${file%.*}.html" ] && mv "${file}" "${file%.*}.html" || printf "%s.html already converted - contacted administrator" "${file%.*}"
done

请注意,也没有任何替换你可以做mv "${file}" "${file}l"

请注意,如果不使用管理用户,使用if-then-else更安全,如下所示:

for file in *.htm; do
  if [ -f "${file%.*}.html" ]; then
    mv "${file}" "${file%.*}.html"
  else
    printf "%s.html already converted - contacted administrator" "${file%.*}"
  fi
done
© www.soinside.com 2019 - 2024. All rights reserved.