Ubuntu: Rename file using regex (Linux Command line)



Question:

I have a backup script which is creating two files:

a) db_mywebsite_2018-01-10_00-25.sql.gz

b) mywebsite1_2018-01-10_00-01.tar.gz

I'm looking for a Linux command with regex to rename both files to match db_mywebsite.sql.gz mywebsite1.tar.gz

The regex command need to remove date (20XX-XX-XX_XX-XX) from file names (each day it will be different).

Thanks for your help!


Solution:1

You must have a look at rename command. It accepts regex patterns.

Usage:

rename [options] [Perl regex search/replace expression] [files]  

From man rename:

-v, --verbose         Verbose: print names of files successfully renamed.  -n, --no-act         No Action: show what files would have been renamed.  

EDIT:

The appropriate regex for your file names is _\d{4}-\d{2}-\d{2}_\d{2}-\d{2}. So you can find this in file names and then replace it with nothing as below:

rename -v -n 's/_\d{4}-\d{2}-\d{2}_\d{2}-\d{2}//' *.sql.gz  

I didn't test above command, but it must work.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »