Rename files in subdirectories

This is how I used bash script to rename all files named ‘old.txt’ to ‘new.txt’ in subdirectories two levels below the current directory.

for f1 in $( ls ); do
    if [ -d $f1 ]; then
        for f2 in $( ls $f1 ); do
            if [ -d $f1/$f2 ]; then
                for f3 in $( ls $f1/$f2 ); do
                    if [ "$f3" == "old.txt" ]; then
                        echo $f3
                        cp $f1/$f2/old.txt $f1/$f2/new.txt
                    fi
                done
            fi
        done
    fi
done
Advertisements

2 thoughts on “Rename files in subdirectories”

    1. oh no, Fail…

      Forget what I said… is wrong, i don’t know what I was thinking about…

      should be like this:

      
      #!/bin/bash
      for file in */*/old.txt; do cp "$file" "${file%/*}/new.txt"; done
      

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s