简体   繁体   中英

bash script renaming all files in current directory as well as all the directories that are above it in hierarchy?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM