This might look a little complex, but it's pretty effective and works well on both *nix and OSX systems. It also acts recursively, renaming files in the current directory as well as any subdirectories:
find . -regex '.*/[0-9]\{7\}[-].*' -print > temp1 && \
cp temp1 temp2 && \
vi -c ":g/\([0-9]\{7\}[-]\)\(.*\)/s//\2/" -c ":x" temp2 && \
paste temp1 temp2 > temp3 && \
vi -c ":g/^/s//mv /" -c ":x" temp3 && \
sh ./temp3 && \
rm temp1 temp2 temp3
Here's a breakdown of what just happened:
The first line says to find (find
) all files, starting with those in the current directory (.
), whose name matches the pattern (-regex
) of "7 numbers, followed by a dash, followed by 0 or more characters" ('.*/[0-9]\{7\}[-].*'
), and write those file names and their respective paths (-print
) to a file called temp1 (> temp1
). Note that the -print
directive is probably not necessary in most cases but it shouldn't hurt anything.
find . -regex '.*/[0-9]\{7\}[-].*' -print > temp1 && \
Then, copy (cp
) the contents of temp1 to a file called temp2.
cp temp1 temp2 && \
Next, open the file temp2 using the vi text editor and give vi two commands (using -c
to signify each new command):
- Command #1:
- Search each line of temp2 (
:g
) for the same pattern we searched for above, except this time group the results using parentheses (\([0-9]\{7\}[-]\)\(.*\)
).
- For each matching line, move the cursor to where the match was found and replace the whole match with only the second group of the matched pattern (
\2
).
- Command #2:
- Save the changes made to temp2 and close the file (
:x
).
The result of which being this:
vi -c ":g/\([0-9]\{7\}[-]\)\(.*\)/s//\2/" -c ":x" temp2 && \
Now, concatenate the lines from temp1 with those of temp2 (paste
) and write each newly combined line to a file called temp3 (> temp3
).
paste temp1 temp2 > temp3 && \
Next, run vi again, doing the same steps as above except this time search for the beginning of each line (^
) inside the file temp3 and add mv and one space right after it (mv
).
vi -c ":g/^/s//mv /" -c ":x" temp3 && \
Then, execute the contents of temp3 (./temp3
) as a shell script (sh
).
sh ./temp3 && \
Finally, remove (rm
) each of the temporary files we created during the whole process.
rm temp1 temp2 temp3