Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bulk renaming files with bash and Perl based on file name

I'm looking to bulk rename files in the current directory only and remove certain strings from the end of file names.

Sample:

foo-bar-(ab-4529111094).txt
foo-bar-foo-bar-(ab-189534).txt
foo-bar-foo-bar-bar-(ab-24937932201).txt

the output should look like this:

foo-bar.txt
foo-bar-foo-bar.txt
foo-bar-foo-bar-bar.txt

I want to remove the string -(ab-2492201) at the end of each file name knowing that the digits can vary in length.

A Perl regex is preferred over modules and without using any utilities and for bash oneliner command is highly preferred.

How to accomplish that in both Perl and Bash Shell on Linux? interested to know both solutions.

like image 426
SilverShadow Avatar asked Jan 09 '13 22:01

SilverShadow


People also ask

Is there a way to rename multiple files at once with different names?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

Can you bulk rename files?

To batch rename files, just select all the files you want to rename, press F2 (alternatively, right-click and select rename), then enter the name you want on the first file. Press Enter to change the names for all other selected files.

Can you automate renaming files?

There are many tools available that can rename files; however, Power Automate is a robust, free, low-code tool can be used to automate tasks in an operating environment comprised of Windows, Microsoft 365 and Azure.


1 Answers

Try:

$ rename 's/-\(ab-\d+\)(?=\.txt$)//' *.txt

There's a rename command written in Perl. Its first argument is Perl code describing how to transform a filename. You could use the same s/// command in your own Perl program or one-liner.

If that doesn't work, try prename instead of rename; there's a different, non-Perl-based, rename command installed on some systems, in which case the Perl one may be called prename.

like image 145
Smylers Avatar answered Oct 12 '22 16:10

Smylers