Table of Contents
Introduction
You can use the rename command or a combination of find and mv commands to batch rename files in a directory with new filenames containing dates in Linux.
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
Command to batch rename files in a directory to new filenames with dates
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"' \;
Explain the command
find
: This command is used to search for files and directories within a specified path. It’s followed by various options that define the search criteria.-name "test[0-9][0-9][0-9].txt"
: This option specifies a pattern to match filenames. The patterntest[0-9][0-9][0-9].txt
will match filenames liketest001.txt
,test002.txt
, up totest999.txt
.-type f
: This option tellsfind
to only search for regular files (as opposed to directories or other types of files).-exec
: This option is used to execute a command on each file that matches the search criteria.sh -c 'mv -f {} "$(dirname {})/$(basename {} .txt)_$(date +%Y%m%d).txt"'
: This part is the command that is executed for each matched file. Let’s break it down further:sh -c
: This runs thesh
shell with the-c
option, which allows you to provide a shell command as a string.mv -f {} "$(dirname {})/$(basename {} .txt)_$(date +%Y%m%d).txt"
: This is the shell command being executed. It consists of several parts:mv -f {}
: This uses themv
command to move (rename) the matched file indicated by{}
. The-f
flag forces the move without prompting."$(dirname {})/$(basename {} .txt)_$(date +%Y%m%d).txt"
: This part constructs the new filename. Here’s how it works:"$(dirname {})"
: Thedirname
command extracts the directory path from the matched file’s path."$(basename {} .txt)"
: Thebasename
command extracts the filename without the extension. The.txt
extension is removed."_$(date +%Y%m%d).txt"
: This adds an underscore followed by the current date in the formatYYYYMMDD
and the.txt
extension to the filename.
\;
: This semicolon signifies the end of the-exec
command for each matched file. It needs to be escaped or quoted to prevent the shell from interpreting it prematurely.
The result is the picture 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 requirement.
I hope will this your helpful. Thank you for reading the DevopsRoles page!