Table of Contents
Introduction
In this tutorial, we’ll explore the process of batch Linux rename file with the inclusion of dates. You can use the rename command or a combination of find commands and mv commands to batch rename files in a directory with new filenames containing dates in Linux.
Linux rename file with Dates
Today I want to share how to batch rename files in a directory to new filenames with dates in Linux only with one command
For example, in my directory, I have files named like this:
- test123.txt
- test456.txt
- test789.txt
The result after running the command looks like this:
“20230805” is the execution date.
- test123_20230805.txt
- test456_20230805.txt
- test789_20230805.txt
Batch Renaming Files with Date Appended
find -name "test[0-9][0-9][0-9].txt" -type f -exec sh -c 'mv -f {} "$(dirname {})/$(basename {} .txt)_$(date +%Y%m%d).txt"' \;
This command searches for and renames files in the current directory (and subdirectories) with names in the format test###.txt
(where ###
represents three digits).
find -name "test[0-9][0-9][0-9].txt"
: Searches for files with names matching the patterntest###.txt
.-type f
: Only searches for files (not directories).-exec sh -c '...' \;
: Executes the shell command for each file found.mv -f {}
: Renames the file (forcing if necessary)."$(dirname {})/$(basename {} .txt)_$(date +%Y%m%d).txt"
: Renames the file by removing the.txt
extension, appending the current date (inYYYYMMDD
format), and then adding back the.txt
extension.
For example, test001.txt
would be renamed to test001_20240812.txt
(assuming the current date is August 12, 2024).
The outcome of rename file in Linux is depicted in the image below:
Conclusion
Remember to back up your files before performing batch operations like this, just to be safe. Also, modify the date format and naming convention as per your requirements. I hope will this be helpful. Thank you for reading the DevopsRoles page!