0

I've found most of the questions of this kind where the change in name has been same for the entire set of files in that directory. But i'm here presented with a situation to give a different name to every file in that directory or just add a different prefix.

For Example, I have about 200 files in a directory, all of them with numbers in their filename. what i want to do is add a prefix of 1 to 200 for every file. Like 1_xxxxxxxx.png,2_xxxxxxxx.png...........200_xxxxxxxx.png

I'm trying this, but it doesnt increment my $i everytime, rather it gives a prefix of 1_ to every file.

echo "renaming files" 
i=1                                             #initializing
j=ls -1 | wc -l                                 #Count number of files in that dir
while [ "$i" -lt "$j" ]                         #looping 
do
    for FILE in * ; do NEWFILE=`echo $i_$FILE`; #swapping the file with variable $i
    mv $FILE $NEWFILE                           #doing the actual rename
    i=`expr $i+1`                               #increment $i
done

Thanks for any suggestion/help.

4

2 回答 2

1

要增加expr,你肯定需要空格(expr $i + 1),但你最好只做:

echo "renaming files" 
i=1
for FILE in * ; do
    mv $FILE $((i++))_$FILE
done
于 2012-12-26T11:42:40.890 回答
1
i=1
for f in *; do
  mv -- "$f" "${i}_$f"
  i=$(($i + 1))
done
于 2012-12-26T11:56:29.833 回答