I'm using the built in Terminal, and I am totally new to this coding so I will need to know exactly what to type when I open the Terminal. Also, please don't direct me to any other software. So lets say...

  • I have a folder named "Power" on my Desktop (without the quotation marks around it of course).

  • In that folder there are multiple .tif files named like the following:

    • Washington,George-150987.tif
    • Lincoln,Abraham-755103.tif
    • Smith,Jack & Jill-102347.tif
    • Jones-Newman,Martha & John Newman-137881.tif
  • These names have one thing in common. They all have a 6 digit number before the extension, and always will.

  • I want a way to batch rename a large group of these files keeping just the last 6 digits. Hell, if there's a code that could rename keeping just numbers, that would be THE BEST, because in rare occasions, there might be a


But if there is no code for that, that's fine, I can use another software to get rid of that (mrs) in a second.

  • Just a small nitpick for your learnings, it would not be called code but command, which can be combined into a script. Since you are using preexisting applications and utilities
    – crasic
    Jan 7, 2016 at 6:15

1 Answer 1


Make a backup of the files first!

Then open Terminal (, start a bash shell if you are not using the default shell) and run

cd ~/Desktop/Power
\ls | while IFS= read f; do echo mv -vn "$f" "${f/*-/}"; done

This will not rename anything but just show how each file will get renamed. If the output looks ok, run

\ls | while IFS= read f; do mv -vn "$f" "${f/*-/}"; done

PS: This assumes that the only - in the file names is the one right before the number.

Some explanations about what's going on here:

  • \ls lists all files, the \ ensures that no alias expansion takes place. The output is fed into a pipe but we do not need to worry about multi-column output because ls in these cases automatically assumes -1
  • while ... do; ...; done loops over all lines/files
  • IFS= read f reads a file name from standard input into $f. The IFS= ensures that none of the characters on standard input confuses read into expecting two values instead of one (technically this is probably not required here, but it's good practice anyway)
  • ${f/*-/} does string substitution on the value of $f, in this case replacing everything up to and including the - with the empty string. See man bash (Parameter Expansion) for details.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .