1

I am trying to rename a few hundred files based on another file in the same directory. I found a script and with modification I have the following:

while read file; do echo mv "\"${file%/*}/Trailer.mov\"" "\"${file%.*}-Trailer.mov\""; done < <(find . -type f ! -name "Trailer.mov" -name "*.mkv")

It outputs mv commands like so:

mv "./dir1/Trailer.mov" "./dir1/filename-Trailer.mov"

The mv commands do rename the files correctly (if it exists) when I run it manually. When I run the script without echo it gives errors like so:

mv: cannot stat ‘"./dir1/Trailer.mov"’: No such file or directory

This error happens for every single item regardless of the files existence. Whyd does this happen? I am running as root.

5
  • Why all of the extra escaped quotes on your mv command? Commented Nov 16, 2014 at 23:06
  • I guess this is a typo: -name "*.mkv" Commented Nov 16, 2014 at 23:09
  • The reason I added extra quotes is to avoid the need to escape each space in the directory and file names. Also, if it's wrong then why did it work when I copy pasted the mv command by hand?
    – DominicM
    Commented Nov 17, 2014 at 0:20
  • You mix up the echo input and output. mv would not work in the shell with the echo input. It just works with the echo output. That's what eval does (in a certain way): It tells the shell: Don't use the input, use the output. Commented Nov 17, 2014 at 4:19
  • @HaukeLaging I am not sure what you mean, it worked just fine outputting mv commands.
    – DominicM
    Commented Nov 17, 2014 at 13:45

1 Answer 1

2

You must either remove the inner quotes or use eval.

The problem is that the "s are now considered part of the file name i.e. the wrong file name (which does not exist) is tried to be accessed.

4
  • Indeed that that was the issue. Can you explain why the mv commands with spaces in the directories worked? That was the only reason I added extra quotes.
    – DominicM
    Commented Nov 17, 2014 at 0:23
  • @DominicM You need quotes to protect whitespace. But you have to levels of quoting. Commented Nov 17, 2014 at 4:17
  • That makes sense but why are there no quotes printed with echo then?
    – DominicM
    Commented Nov 17, 2014 at 13:47
  • 1
    @DominicM Because echo doesn't see the quotes. Quotes are to be seen by the shell only. They tell the shell where an argument begins and where it ends. They are not part of the argument. Unless you escape quotes (like you did what caused the problem). Then the quotes are no quoting characters any more and become part of the argument; which may be desired for optical reasons with echo but must not be done when file names are accessed. Commented Nov 17, 2014 at 15:47

You must log in to answer this question.

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