Ubuntu – Changing extension of multiple files in Ubuntu 12.04


As the title says, how can I change the extension of every file in a directory in Ubuntu? I've seen some examples use rename etc etc but I get an error (Unable to locate package rename) and it's not accessible through apt-get.

As an additional, I don't actually know the original file type! It's data that's been copied from the file system of Hadoop to the local drive and I need them all to be in .txt format.

If it makes a difference, I'm running Ubuntu 12.04 in Oracle Virtual Box

Edit: Output of:
ls -l /usr/bin/rename /etc/alternatives/rename

amartin24@ubuntu-amartin24:~/TwitterMining/JSONTweets$ ls -l /usr/bin/*rename* /etc/alternatives/rename
ls: cannot access /etc/alternatives/rename: No such file or directory
-rwxr-xr-x 1 root root 10392 Mar 30  2012 /usr/bin/rename.ul

Best Answer

You could cd to the directory in question and execute something similar to this:

find -L . -type f -name "*.oldextension" -print0 | while IFS= read -r -d '' FNAME; do
    mv -- "$FNAME" "${FNAME%.oldextension}.newextension"

Or if the files don't have any extension at all:

find -L . -type f -print0 | while IFS= read -r -d '' FNAME; do
    mv -- "$FNAME" "${FNAME%}.newextension"

In your case you would have to replace newextension with txt.

Someone more proficient with bash might be able to break this down better. Please feel free to edit my answer in that case.

Original description:

1) It will rename just the file extension (due to use of ${FNAME%.so}.dylib). All the other solutions using ${X/.so/.dylib} are incorrect as they wrongly rename the first occurrence of .so in the filename (e.g. x.so.so is renamed to x.dylib.so, or worse, ./libraries/libTemp.so-1.9.3/libTemp.so is renamed to ./libraries/libTemp.dylib-1.9.3/libTemp.so - an error).

2) It will handle spaces and any other special characters in filenames (except double quotes).

3) It will not change directories or other special files.

4) It will follow symbolic links into subdirectories and links to target files and rename the target file, not the link itself (the default behaviour of find is to process the symbolic link itself, not the file pointed to by the link).


Bash rename extension recursive - stackoverflow, answered by aps2012.

Related Question