Markys
Markys

Reputation: 33

Batch renaming files in MAC OSX

I have several thousand files with name like this:

PIN_PMN_PT_010_02_00331_0004_018edf

and need to rename them all something like this:

PIN_PMN_PT_010_02_00331_0004_018.edf

I have used simple mv scripts like this:

for f in *; do echo mv "$f" "`echo $f | tr 'edf' '.edf'`"; done

For some reason it creates names like this:

PIN_PMN_PT_010_02_00331_0004_018.ed

They are missing the last f. I am running the script using echo to dry run. Any ideas please?

Using MACBook Pro running Mohave 10.14.6 and Bash.

Upvotes: 1

Views: 96

Answers (3)

F. Hauri  - Give Up GitHub
F. Hauri - Give Up GitHub

Reputation: 70792

Use shell Parameter Expansion!

Simply under any :

For the test, echo to show what's will go:

for file in *edf ;do echo mv "$file" "${file%edf}.edf" ;done

Then, for doing the job:

for file in *edf ;do mv "$file" "${file%edf}.edf" ;done

(This must work same on MacOs, than under Linux.)

... And to prevent renaming of already correctly named files:

for file in *edf ;do test -f "${file##*.edf}" && mv "$file" "${file%edf}.edf" ;done

Syntax ${file##*.edf} will replace any string, terminated by .edf, by an empty string. So test -f "" will fail.

... Still: I don't have any Mac for doing the test, but as this is POSIX Standard, this must work on any . (Let my know, please comment!)

More infos?

Have a look at man sh or man bash and search for Parameter Expansion

man -P"less +'/Parameter Expansion'" bash

Upvotes: 4

Mark Setchell
Mark Setchell

Reputation: 207465

Personally, I find the rename command invaluable for this sort of thing:

rename 's/edf$/.edf/' *edf

If you want to do a dry-run, you can do:

rename --dry-run 's/edf$/.edf/' *edf

Sample Output

'PIN_PMN_PT_010_02_00331_0004_018edf' would be renamed to 'PIN_PMN_PT_010_02_00331_0004_018.edf'

The benefits of using rename are:

  • it can do a dry-run to test before you run for real
  • it will create all necessary directories with the -p option
  • it will not clobber (overwrite) files without warning
  • you have the full power of Perl available to you and can make your renaming as sophisticated as you wish.

As helpfully suggested by F. Hauri in the comments, you may have some files that have already had the dot inserted before the extension in your directory. To protect against insertion of a second dot, you could either be more specific in the files you select for renaming and only rename those ending in a digit followed by edf:

rename 's/edf$/.edf/' *[0-9]edf

Or, as F.Hauri suggested:

rename 's/([^.])edf$/$1.edf/' *edf

Note that you can install on macOS with homebrew:

brew install rename

Upvotes: 0

beninato
beninato

Reputation: 420

Using sed, this should work

for f in *; do echo mv "$f" "`echo $f | sed 's/.\{3\}$//`.edf"; done

You are just removing the last 3 characters of a string, and adding your file extension.

Upvotes: 0

Related Questions