具有空格的文件被视为单独的文件

时间:2018-04-05 00:05:29

标签: find

如何修改脚本以不将带空格的文件视为单独的文件?

thetime=`date +%Y-%m-%d_%H:%M:%S` #
for i in $(find . ! -name "*.filepart")
do
         extn=${i##*.} # save the extension of the file
                 mv "$i" "${i%.*}"$(date "+_%Y-%m-%d_%H:%M:%S.${extn}")
done

mv: cannot stat ‘./user1/upload/Axle’: No such file or directory
mv: cannot stat ‘Assy’: No such file or directory
mv: cannot stat ‘Removal.doc’: No such file or directory

#find . ! -name "*.filepart"
#./user1/upload/Axle Assy Removal.doc

1 个答案:

答案 0 :(得分:0)

这不适用于名称包含空格的文件:

for i in $(find . ! -name "*.filepart"); do   # Fail

以下两种方法适用于所有文件名:

方法1:使用-execdir

find . -type f ! -name "*.filepart" -execdir sh -c 'f=$(basename "$1"); mv "./$f" "./${f%.*}$(date "+_%Y-%m-%d_%H:%M:%S")${f#${f%.*}}"' Mv {} \;

方法2:使用-print0

find . -type f ! -name "*.filepart" -print0 | while IFS= read -r -d $'\0' file
do
    d=$(dirname "$file")
    f=${file#$d}
    mv "$d$f" "$d${f%.*}$(date "+_%Y-%m-%d_%H:%M:%S")${f#${f%.*}}"
done

进一步阅读

How can I find and safely handle file names containing newlines, spaces or both?