Ubuntu – How to rename a group of files with what looks like a Windows file path in their names

batch-renamecommand linerename

I got a bunch of files with the filename messed up. All the file names have the same beginning which appear to be windows file directories. The problem is there are 700+ files and I really don't want go through and manually rename all of them. These are examples of the file names (Note: None of these have file directories):

G:some\really\long\file\path\then\the\name1.jpg
G:some\really\long\file\path\then\the\name2.png
G:some\really\long\file\path\then\the\filename.txt
G:some\really\long\file\path\then\the\file_name.mov
...

The important take away is that each file has G:some\really\long\file\path\then\the\ before the file name that I would like.

So I would want the above files to look like:

name1.jpg
name2.png
filename.txt
file_name.mov

I've tried the rename command and was not successful. I am still new with Linux and really am not sure on how to go about it or really what to google. Any help would be appreciated.

Best Answer

I just removed everything up to the last backslash with rename

$ rename -n 's/.*\\//' G*
rename(G:some\really\long\file\path\then\the\file_name.mov, file_name.mov)
rename(G:some\really\long\file\path\then\the\filename.txt, filename.txt)
rename(G:some\really\long\file\path\then\the\name1.jpg, name1.jpg)
rename(G:some\really\long\file\path\then\the\name2.png, name2.png)

Remove -n after testing to actually rename the files.

Notes

  • -n don't do anything, just print what will be changed
  • s/old/new replace old with new
  • .* any number of any characters
  • \\ The first backslash is to escape the second one.
  • Since regex are greedy this expression .*\\ eats all the preceding backslashes too.
  • Since the last two delimiters // are empty everything matched in the search part is deleted