0

I have a group of files with a set prefix, and I would like to change that prefix on all of the files simultaneously in terminal. So let's say I wanted to change this group

01-here.md
01-is.md
01-an.md
01-example.md

to this

02-here.md
02-is.md
02-an.md
02-example.md

I'm looking for something along the lines of mv 01*.md 02*.md, but that doesn't work. After digging around a bit I found an easy way to accomplish the same task using finder, but finder is for slowpokes and losers, obviously, so I still want to know how to do it "for realz."

EDIT: Using OS X

devigner
  • 152
  • 12
  • 1
    You didn't state what OS and what shell you are using. – Not Important Mar 02 '16 at 21:26
  • He said "in Terminal" and not "in _the_ terminal," (and he also mentioned Finder) so I'm assuming it's OSX. Ordinarily, the [batch-file] tag would mean this question is exclusively for Windows, but people confuse it with the [batch-processing] tag way more than they should. – SomethingDark Mar 02 '16 at 22:53
  • Correct on both counts, @SomethingDark. Fixed. – devigner Mar 02 '16 at 23:58

4 Answers4

1

You can try something like this (edited answer):

INITIAL_SUFFIX="01-";
FINAL_SUFFIX="02-";

for file in $(ls -1 "$INITIAL_SUFFIX"*); do
        if [ -f $file ]; then
                mv $file "$FINAL_SUFFIX${file#*-}";
        fi;
done
delephin
  • 1,085
  • 1
  • 8
  • 10
  • Not quite. This renames all files and folders in the working directory, regardless of whether or not they share a prefix. – devigner Mar 03 '16 at 00:32
1

For your example situation, try

for f in *.md; do echo mv "$f" "${f/2/3}"; done

(Note: the echo will just show you what will happen, remove it to actually rename files). A good explanation of this excerpt can be found here.

On another note, you could do this in Applescript or Automater too, both of which offer a solid amount of functionality for batch renaming and whatnot.

Community
  • 1
  • 1
Lawrence
  • 862
  • 1
  • 7
  • 15
1

I have a script called rename for this, but if I didn't, I would use a loop, something like this:

for f in 01-*.md; do mv "$f" "${f/01/02}"; done
Mark Reed
  • 91,912
  • 16
  • 138
  • 175
0

The easiest, most flexible way to do this is with the Perl rename script. On OSX, it can easily be installed with homebrew, using

brew install rename

Then you can do:

rename 's/01/02/' *md

If you want to just see what it would do, without actually doing anything, use the --dry-run option as follows:

rename --dry-run 's/01/02/' 01*md

Output

'01-an.md' would be renamed to '02-an.md'
'01-example.md' would be renamed to '02-example.md'
'01-here.md' would be renamed to '02-here.md'
'01-is.md' would be renamed to '02-is.md'

It also will not overwrite any files if they work out to the same resulting filename and can do much, much more sophisticated renaming.

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432