Ds1715
Ds1715

Reputation: 41

Fish: batch rename files with spaces in names using mv and sed

I'm trying to rename multiple files from the command line as follows:

for f in *.pdf
    mv $f echo $f | sed 's/\( \)\([0-9]\)/-\2/'
end

I got the error:

mv: target 'filename' is not a directory

It is obvious that target's name has spaces and must be enclosed in quotes to be handled by mv command.

What should I do to get this script works?

Upvotes: 1

Views: 1132

Answers (1)

faho
faho

Reputation: 15974

Your script will try to move the file and the file called "echo" to the file, and pipe mv's output to sed.

What you want is to run that echo | sed in a command substitution, which fish denotes with ():

for f in *.pdf
    mv $f (echo $f | sed 's/\( \)\([0-9]\)/-\2/')
end

It is obvious that target's name has spaces and must be enclosed in quotes to be handled by mv command.

It is not obvious because it doesn't need to be quoted. Fish does not perform word splitting like bash does. The filename is set once, and then $f will always yield the filename as one argument.

Quoting it like "$f" would be entirely superfluous.

For command substitutions, it splits them on newlines only, not spaces, so unless you have a filename with a newline (highly unlikely) you won't have a problem there either.

If you did you'd have to use string collect like

for f in *.pdf
    mv $f (echo $f | sed 's/\( \)\([0-9]\)/-\2/' | string collect)
end

to ensure the command substitution results in one argument.

Upvotes: 1

Related Questions