我正在尝试编写一个基于文件扩展名重命名文件的脚本。 该脚本应提示用户提供所需的文件扩展名。接下来,它应该询问用户前缀文件名的前缀。默认前缀应为今天的日期,格式为YYYY-DD-MM。
因此,如果用户按下输入,则应使用今天的日期作为默认值。否则,它将使用用户输入的任何前缀。之后,我希望它在同一行显示原始文件名和文件的新名称,最后应重命名该文件:
这就是我想要输出
的方式示例输出1:
Please enter a file extension: gif
Please enter a file prefix: (Press ENTER for 20180219). helpme
Renaming goose.gif to helpmegoose.gif.
示例输出2:
Please enter a file extension: gif
Please enter a file prefix: (Press ENTER for 20180219).
Renaming goose.gif to 20180219goose.gif.
这是我到目前为止的代码:
#!/bin/bash
cd /c/Users/johndoe/unix
curr=$(date +"%Y-%m-%d")
echo -n "Please enter file extension: " ; read extension
echo -n "Please enter a file prefix(Press ENTER for ${curr}) " ; read prefix
if [ -e $extension ]
then
for FILES in /c/Users/johndoe/unix/*.$extension
do
echo -n "Renaming ${FILES} to " ; mv ${FILES} $prefix${FILES};
done
else
echo -n "Renaming ${FILES} to " ; mv ${FILES} $curr${FILES};
fi
答案 0 :(得分:1)
#!/usr/bin/env bash
cd /c/Users/johndoe/unix || exit 1
curr=$(date +"%Y-%m-%d")
IFS= read -rp "Enter file extension: " ext
IFS= read -rp "Enter prefix (ENTER for $curr): " prefix
shopt -s nullglob
for file in *".$ext"; do
printf 'Renaming %s to %s.\n' "$file" "${prefix:-$curr}$file"
mv -- "$file" "${prefix:-$curr}$file"
done