Linux rename file with Dates in Batches

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
Linux rename file with Dates in Batches

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 pattern test###.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 (in YYYYMMDD 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:

How to batch rename files in a directory to new filenames with dates in Linux

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!

About Dang Nhu Hieu

I'm Vietnamese. In the past, I'm a software developer, now working in Japan on an Infra team. Skill : AWS, VMware, HA architech,setting Database : Oracle DB, PostgresDB ,.. Programming language : Java, C#, Python, Bash linux, Batch windows, powershell ,... Hobbies: badminton, film photo, travel. https://www.linkedin.com/in/hieu-dang-15a0561a6/
View all posts by Dang Nhu Hieu →

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.