Rename file using regex (Linux Command line)

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!

1

1 Answer

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like