3

I want to rename all files which end on ".mp4" in such way that instead of white spaces to contain underscores. Example:

Original file -> test 1.mp4
Renamed file -> test_1.mp4

I was trying with:

find . -iname "*.mp4"  -exec mv {} $(echo '{}' | tr " " "_") \;

But I got only:

mv: ‘./test 1.mp4’ and ‘./test 1.mp4’ are the same file

It seems that my pipe is not working.I would appreciate all ideas.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
hunter86bg
  • 37
  • 1
  • 3
  • try `find . -iname "*.mp4" -exec mv "{}" $(echo '{}' | tr " " "_") \;` Good luck. – shellter Aug 13 '17 at 20:53
  • Possible duplicate of [Recursively rename files using find and sed](https://stackoverflow.com/questions/4793892/recursively-rename-files-using-find-and-sed) – jww Jun 08 '18 at 15:22

2 Answers2

-1

I'd look into using the rename command, assuming your distribution provides it. In Debian: https://packages.debian.org/rename

If you don't need to search in subdirectories:

rename 's/\ /_/' *.mp4

If you do:

find . -iname "*.mp4" -execdir rename 's/\ /_/' {} \;

If multiple spaces must be replaced, the search/replace expression becomes 's/\ /_/g'

If you really want to keep your syntax/approach, see this very similar question: find -exec with multiple commands

jmr
  • 196
  • 1
  • 1
  • 10
  • As the search will be recursive the "find" way should be more appropriate, but it gives an error: [code]$ find . -iname "*.mp4" -exec rename 's/\ /_/' {} \; rename: not enough arguments[/code] – hunter86bg Aug 13 '17 at 19:47
  • I've been unable to reproduce your error. I'm assuming that your distro (which one is it?) has a different command that answers to "rename". But in my tests, I found that my recursive answer will fail (with a different error) when encountering directories whose names contain spaces. I've therefore removed that part of the answer. – jmr Aug 13 '17 at 20:05
  • The distribution is CentOS 7. Indeed "rename" exists , but I have never managed to make it work. – hunter86bg Aug 13 '17 at 20:07
  • I saw your answer, glad you found a solution that works for you. I've fixed and re-added my recursive solution - you might want to look into -execdir instead of -exec in yours too, in case your directory names contain spaces too. And remember, man is your friend :-) – jmr Aug 13 '17 at 20:18
  • As you've already found out, CentOS's rename is indeed different: http://www.unix.com/man-page/centos/1/rename/ – jmr Aug 13 '17 at 20:27
-1

It seems that the only way to do it so far is via "rename" command.

Here is the command that worked:

find /tmp/test/ -iname "*.mp4" -exec rename " " "_" "{}" \;
hunter86bg
  • 37
  • 1
  • 3