macosshellsedzsh

How to rename files using Zsh shell and `sed` command on Mac OSX


I have a folder on my desktop called "Images", inside that folder are 3 images...

File-A-B.gif
File-C-D.gif
File-E-F.gif

...I want to rename the files on the command line so the second hyphen/dash is removed. So the result would be files named like so...

File-AB.gif
File-CD.gif
File-EF.gif

...I'm using a combination of commands piped through to each other but not having much luck in getting them to work.

Initially I had ls File-* | sed 's/\(File-[^-]\)-\(.+\)/mv & \1\2/' | sh

The break-down of this command is...

  • list out any files that begin File-
  • pipe the results through to sed
  • we'll use sed to capture different parts of the name
  • looking at the first file we'll capture the File-A and the B.gif
  • with sed we then replace the matched file name with a move command and effectively tell it to rename the original file to a file made up of the two pieces of data we've captured
  • we then pipe that command through to sh

The initial error I was getting was a permissions error. I'm not sure why as I had 'read and write' access to the files.

To work around this I chmod 777 each of the files.

This then resulted in a new error which was cannot execute binary file.

To work around that error I saw this post: http://blog.mpdaugherty.com/2010/05/27/difference-with-sed-in-place-editing-on-mac-os-x-vs-linux/ which suggests adding an extra pair of single quotes. The reason this works (apparently) is because sed will error because it doesn't know what file extension to use, but putting an empty String neutralises that error (on a side note: my understanding was that you also need to use the -i flag - which I'm not using - but doing that caused a different error so I scrapped that and just used the single quotes to avoid the binary file error I was getting).

So now I have ls File-* | sed '' 's/\(File-[^-]\)-\(.+\)/mv & \1\2/' | sh

But this errors with No such file or directory?

I tried to be explicit with the location of the file, so for example...

ls File-* | sed '' 's/\(File-[^-]\)-\(.+\)/mv ~\/Desktop\/Images\/& ~/Desktop\/Images\/\1\2/' | sh

...notice I've had to escape the forward slashes ~\/Desktop\/Images\/ but this still didn't work.

I also installed the GNU version of sed using Homebrew but it also errored in a similar way with gsed: can't read s/\(Vim-[^-]\)-\(.+\)/mv & \1\2/: No such file or directory

I'm a bit at a loss with how I can get this to work.

I don't want to have to resort to writing a bash/zsh script or a Ruby script.

Any help you can give me would be greatly appreciated.


Solution

  • The following should work for you:

    ls File-* | sed 's/\(.*\)-\(.*\)/mv & \1\2/' | sh
    

    What you tried

    ls File-* | sed '' 's/\(File-[^-]\)-\(.+\)/mv & \1\2/' | sh
    

    was pretty close. Saying:

    ls File-* | sed '' 's/\(File-[^-]*\)-\(.*\)/mv & \1\2/' | sh
    

    instead would have worked.