How to rename all files in the same folder with different/random extentions in a directory on linux?

Viewed 69

Lets say I have 28k files in a folder with different random file name extensions.... See example:

br.AQ5702419254531904.GD14700006
br.CT7465737800862080.MV94400009
etc
etc
br.RH5816804080109504.BE59800003
etc
ect
etc

28k later...

How would i change them all to

br.AQ5702419254531904.GD14700006.txt or *.json
br.CT7465737800862080.MV94400009.txt or *.json
br.RH5816804080109504.BE59800003.txt or *.json

3 Answers

You could use a script like this:

while read -r path; do
  mv -v "${path}" "${path}.txt"
done < <(find . -type f -not '(' -name '*.txt' -or -name '*.json' ')' )

This invoke find (and also work on file in directories), ignoring txt/sjon, and renaming file with *.txt.

You may also do that directly on the command line:

find . -type f -not '(' -name '*.txt' -or -name '*.json' ')' | while read -r path; do mv -v "${path}" "${path}.txt"; done

However, still will create a subprocess.

You can also use the rename command (which can accept regex):

rename 's/(br[.][A-Z0-9]{18}[.][A-Z0-9]{10})/\1.txt/g' *

If you wanted your regex to be broken down into multiple sets to make it more dynamic, you could do something like this:
rename 's/(br[.])([A-Z0-9]{18}[.])([A-Z0-9]{10})/\1\2\3.txt/g' *

This is a contrived example, but if you needed to do something like make br.AQ5702419254531904.GD14700006 into br.GD14700006.AQ5702419254531904.txt, you can do:

rename 's/(br[.])([A-Z0-9]{18}[.])([A-Z0-9]{10})/\1\3\2.txt/g' *

You'll notice that I flipped the remembered patterns, so that it was \1\3\2 to make that change. Everything contained in it's own set of parenthesis constitutes a group for the remembered pattern.

You just have to put 'em in a loop, you can use 'for':

#!/bin/bash

DIR="<your_directory_path>"
cd $DIR

for FILE in `ls $DIR`
do

mv $FILE $FILE.txt

done
Related