Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to batch rename files in OS X Terminal

I'm after a way to batch rename files with a regex i.e.

s/123/onetwothree/g 

I recall i can use awk and sed with a regex but couldnt figure out how to pipe them together for the desired output.

like image 439
user370507 Avatar asked May 19 '12 10:05

user370507


People also ask

How do I batch rename multiple files at once?

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.

How do I rename multiple files in Terminal Mac?

You can drag the cursor to select multiple with a box, or shift-click or Command-click the files, or in the Menu, select Edit then Select All. With the files selected, either right-click the selected files and select Rename, or go to File then Rename in the Menu.

Is there a way to batch 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 batch rename files on Mac?

Rename multiple itemsOn your Mac, select the items, then Control-click one of them. In the shortcut menu, choose Rename. In the pop-up menu below Rename Finder Items, choose to replace text in the names, add text to the names, or change the name format.


2 Answers

You can install perl based rename utility:

brew install rename 

and than just use it like:

rename 's/123/onetwothree/g' * 

if you'd like to test your regex without renaming any files just add -n switch

like image 199
Viperet Avatar answered Sep 18 '22 19:09

Viperet


An efficient way to perform the rename operation is to construct the rename commands in a sed pipeline and feed them into the shell.

ls | sed -n 's/\(.*\)\(123\)\(.*\)/mv "\1\2\3" "\1onetwothree\2"/p' | sh 
like image 37
Diomidis Spinellis Avatar answered Sep 19 '22 19:09

Diomidis Spinellis