如何从具有x位数字前缀的文件名中删除前缀

时间:2014-11-27 02:20:55

标签: bash if-statement

在社区的帮助下,我将以下脚本放在一起,为所有文件添加x位随机前缀。问题是,有时我需要添加一个新文件,那就是当我的脚本遇到麻烦时

#!/bin/bash

# validate input
[ -n "$1" ] || {
    printf "error: insufficient input. Usage: %s /path/to/files\n" "${0//\//}"
    exit 1
}

# validate directory
[ -d "$1" ] || {
    printf "error: directory not found: '%s'\n" "$1"
    exit 1
}

path="$1"

## removing prefix
count=$(ls $path | cut -c1-10 | uniq | wc -l)
echo $count
echo $path
if [ $count = "1" ]
then
cd $path
for i in *; do mv "$i" `echo $i|cut -c11-`; done
echo "PREFIXES REMOVED"
else
echo "PREFIXES ARE NOT UNIQUE, SKIPPING"
fi

mask=$RANDOM$RANDOM$RANDOM; let "mask %= 10000000000";
len=$(echo ${#mask})
## Note: this assumes you are exporting mask earlier. If not, set mask here
## add validation for length 10
if [ $len -lt 10 ]; then
echo "mask is not 10" >&2
exit 1
fi
# move files
prefixcheck=$(ls $path | cut -c1-10 | uniq | wc -l)
if [ $prefixcheck != 1 ]
then
for i in "${path}"/*; do

    [ -f "$i" ] || continue  # if not file, skip

    dir="${i%/*}"            # path component
    ffname="${i##*/}"        # full filename component (with .ext)

    mv "$i" "${dir}/${mask}${ffname}"
    echo $mask " applied at " $(date) "in " $path >> /home/newprefix
done
else
echo "prefixes exist, skipping"
fi

假设我有20个带前缀的文件,我在文件夹中放入了一个新文件recording001.mp4,然后我的脚本将失败。如何告诉它从文件名中字符1-10为数字的所有文件中删除前缀?

1 个答案:

答案 0 :(得分:1)

从文件名中删除10位前缀:

cd "$path" &&
for i in [0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*
do
     mv "$i" "${i#??????????}"
done