Reputation: 1707
I have written following script to rename all the files within all the folders of the current directory. But I got into problem because its not only renaming the files within folder but also all the folders in current directory and parent directories in hierarchy. I realised that this is because of . and .. present in current directory. But how to get rid of them ?
for i in *
do
cd $i
for j in *
do
mv $j $i$j
done
cd ..
done
The problem is, I have many folders and they contain images that are named as image0001 to image0100. And I want to copy all of the images to one folder. So they are overwriting each other. That is why I want to rename the images.
Upvotes: 0
Views: 174
Reputation: 183321
I think what's going wrong is probably that cd $i
is sometimes failing (perhaps because $i
is not a directory? or perhaps because it contains spaces, so triggers word splitting?), so then you stay in the same directory, and then cd ..
moves you up a directory.
To fix this (and other potential issues that could crop up), I recommend making your script a bit more cautious:
for dir in */ ; do
pushd "$dir" || continue
for file in image???? ; do
mv "./$file" "${dir%/}$file"
done
popd
done
Upvotes: 4