将.tmp文件重命名为.TIF

时间:2014-07-17 17:11:43

标签: bash

我有一个脚本来重命名今天修改过的文件列表。我希望它在生成列表和重命名文件之间延迟,以确保它们已完全下载。下载由外部进程控制,大多数文件小于1MB,因此在处理之前等待一分钟就足够了。 如果我用下面的代码替换下面程序中的while循环它可以工作,但我担心它会重命名一个正在下载的文件。

find . -mtime -1 -type f | grep .tmp | cut -c 3-19 | while read i ; do

程序

read file_list <<< $(find . -mtime -1 -type f | grep .tmp | cut -c 3-19)
echo $file_list
read -r -p "Were the correct filenames selected (Y/N):" prompt
if [[ $prompt == "y" || $prompt == "Y" ]]
then
    sleep 1m;
    while $file_list ; do
            echo 'mv '$i'.tmp '$i'.TIF'
            mv $i.tmp $i.TIF
    done
    echo 'Renaming complete';
else
    echo 'No action taken';
    exit 0
fi

注意: 这个程序只是一个临时修补程序,用于清理另一个程序(由其他人创建)遗留下来的一个无法正常运行的混乱。

2 个答案:

答案 0 :(得分:4)

这是一个减少错误的脚本:

# read files into an array; this fixes support for files with spaces, wildcard
# characters, newlines, etc. in their names.
declare -a file_list=()
while IFS='' read -r -d '' file; do
  fuser -- "$file" >/dev/null && continue # skip files which are open
  file_list+=( "$file" )
done < <(find . -mtime -1 -name '*.tmp' -type f -print0)

# use printf '%q' to format nonprintable characters readably.
printf '%q\n' "${file_list[@]}"
read -r -p "Were the correct filenames selected (Y/N):" prompt
if [[ $prompt == "y" || $prompt == "Y" ]]; then
    for file in "${file_list[@]}"; do
      mv -i -- "$file" "${file%.tmp}.tif"
    done
    echo 'Renaming complete';
else
    echo 'No action taken';
    exit 0
fi

请参阅fuser命令,该命令检查文件是否已打开。


有人提到下载实际上发生在一个完全不同的系统上。这意味着fuserinotify样式方法都无法使用。

如果您确信下载时间不会超过5分钟,则find命令可以更改如下:

find . -mtime -1 -mmin +5 -name '*.tmp' -type f -print0

答案 1 :(得分:1)

您可以随时使用

sleep 2m  # minutes (in GNU sleep only; POSIX sleep would need 120)

sleep 5   # seconds

...列表检索和重命名操作之间。