Mass Changing File Names or Adding Extensions

When I am working on a script that creates a number of files or backups, it is really helpful to be able to change all of the filenames at once to have a new file extension or prefix the filenames with something.

For example, say I run a backup script, but I forget to include to include the date in the parameters when I ran it. I now have 40 files, but they don’t include the date in the file name. Let’s say that today’s date is March 22, 2233. On a command line, I can run:

for i in *; do mv "$i" "22330322-$i"; done

This will take all of the files in the current directory and prefix them all with the year, month, day, and then a hyphen. What if you need to add or change a filename? For example, if you export a bunch of CSV files, but they come out with no file extensions. You could add a .csv to all files with:

for i in *; do mv $i $i.csv; done

Or if you make txt files, but actually want them to be CSV files, you can change them all using:

for i in *; do mv $i ${i/.txt/.csv}; done

Or, if you accidentally made a double file extension, like “filename.txt.csv”, you can remove the superfluous .txt using:

for i in *; do mv $i ${i/.txt/}; done

Or, let’s say you have a bunch of CSV and PDF files in a folder. You accidentally have some that have an extension of .pdf.csv and you want to remove the “.pdf” only from the CSV files, not from the PDF files. You could use:

for i in *.csv; do mv $i ${i/.pdf/}; done

Just make sure you are really careful with what you are selecting and changing!

Leave a Reply

Your email address will not be published. Required fields are marked *