Rename folders from [FIRST NAME] [LAST NAME] to [LAST NAME] [FIRST NAME]

Hi all

First of all thank you for any help you might be able to offer.

I’m looking at renaming a few hundred customer folders. They are currently formatted [FIRST NAME] [LAST NAME] and I would like to see if there is a way to rename these as [LAST NAME] [FIRST NAME]

Is this possible with macOS 11 itself, or could someone recommend an application which could help (hopefully free)

Thanks again :slight_smile:

IMPORTANT: Backup your customer directories before doing this.

You always want to be able to undo or restore it just in case something does not meet your needs.


This approach just uses built in command line utilities.

Open the terminal app and cd to the directory holding your customer folders. This is a vital step. Make sure you run this command exactly where you need to.

Enter the following line:

ls -d * | sed -n 's/\(.*\) \(.*\)/mv "\1 \2" "\2 \1"/p' | sh

The first part, before the first pipe, lists the directories.

The second part uses the stream editor (sed) and some regular expressions to build some move (mv) commands. One for each directory.

e.g. mv "john smith" "smith john"

The final part simple shell executes the commands generated.

To see the commands to be executed without executing them just remove the “ | sh” from the end of the command. That’s a good double check before running it.

One useful thing to note is that this renaming, if run a second time, should reverse the effects if all of the folder names were in the correct initial format.

Hope that helps.

1 Like

Thank you, thank you. Works great :slight_smile:

That’s pretty darn clever!

One question, however… on my system ls -d * will show directories and files if both are present in the current folder.

If I want to show just directories, I use:

ls -dFC *(/)

but that might be zsh-specific.

1 Like

Could well be. I was on my work PC when I did it and tested remotely on my Mac mini which I don’t think defaults to zsh. I know my Macbook defaults to fish, but I just can’t remember what the mini is on these days.

1 Like

I double-checked and ls -dFC *(/) does not work in bash and ls -d will show all files and folders, so just be aware of that if you are in a folder with both.

2 Likes

I think this should work in a directory which has both files and folders/directories in it, but only act on the folders themselves:

find * -type d -maxdepth 0 -print 2>/dev/null | while read line
do
echo "$line" | sed -n 's/\(.*\) \(.*\)/mv "\1 \2" "\2 \1"/p' | sh
done

It’s using basically the same command that @sylumer came up with to do the actual renaming, but using find instead of ls to get the list of folders/directories.

Command Interpretation
find * -type d “only find directories”
-maxdepth 0 “only in the current directory”
-print “output a list”
2>/dev/null “disregard errors”
2 Likes