bash错误使用空格重命名文件 - mv目标不是一个目录 [英] bash error renaming files with spaces - mv target is not a directory
问题描述
我试图重命名一堆包含空格的文件,摆脱空格。我以为我找到了正确的bash命令:
pre $ f $ in * .txt;做mv \$ f \$ {f / /};完成
然而,这给出了错误,mv:target不是每个文件的目录。如果我在命令中用'echo mv'替换'mv',它会为每个文件打印适当的mv命令,如果我单独键入这些mv命令中的任何一个,它们都会工作。例如,如果我有2个文件,a .txt和b .txt,并运行上面的命令,我得到:
mv:target'a.txt'不是目录
mv:target'b.txt'不是目录
如果输入以下命令:
for f in * .txt;做echo mv \$ f \$ {f / /};完成
我得到:
mva .txta.txt
mvb .txtb.txt
我找到了另一种方法来做到这一点,使用重命名,但我想知道为什么这不起作用。
试试:
for f in * .txt;做mv$ f$ {f // /};完成
三点:$ b
$ b
-
一个shell变量的引号不应该被转义。
-
一般来说,把双引号围绕每个引用一个shell变量。
-
$ {f / /}
的空间。要删除所有空格,请使用$ {f // /}
。
出了什么问题
$ touch {a,b}.txt
$ ls *。 txt
a .txt b .txt
$ for f in * .txt;做mv \$ f \$ {f / /};完成
mv:target`a.txt'不是目录
mv:target`b.txt'不是目录
表达式
\$ f \
的行为不像双引号。它扩展为两个参数,如a
和.txt
,其中双引号被视为正常字符,就像a
是一个普通字符。因为有三个参数mv
(a
和.txt
和a.txt
),mv
相信您正试图将前两个参数移动到第三个第三个要求是一个目录。由于第三个不是目录,因此会发出错误消息。I'm trying to rename a bunch of files which contain spaces in them, getting rid of the spaces. I thought I found the correct bash command:
for f in *.txt; do mv \"$f\" ${f/ /}; done
However, this gives the error, "mv: target is not a directory" for each file. If I replace 'mv' with 'echo mv' in the command, it prints the proper mv command for each file, and if I type any of those mv commands individually, they work. For example, if I have 2 files, "a .txt", and "b .txt", and run the command above, I get:
mv: target 'a.txt' is not a directory mv: target 'b.txt' is not a directory
If I type the command:
for f in *.txt; do echo mv \"$f\" ${f/ /}; done
I get:
mv "a .txt" a.txt mv "b .txt" b.txt
I've found another way to do this, using "rename", but I would like to know why this doesn't work.
解决方案Try:
for f in *.txt; do mv "$f" "${f// /}"; done
Three points:
The quotes around a shell variable should not be escaped.
In general, it is a good idea to put double-quotes around every reference to a shell variable.
${f/ /}
removes just the first occurrence of a space. To remove all spaces, use${f// /}
.
What went wrong
$ touch {a,b}" .txt" $ ls *.txt a .txt b .txt $ for f in *.txt; do mv \"$f\" ${f/ /}; done mv: target `a.txt' is not a directory mv: target `b.txt' is not a directory
The expression
\"$f\"
does not behave like it is double quoted. It expands to two arguments, such as"a
and.txt"
, where the double-quotes are treated as normal characters, just like thea
is a normal character. Because there are three arguments tomv
("a
and.txt"
anda.txt
),mv
believes that you are trying to move the first two arguments to the third and the third is required to be a directory. Since the third is not a directory, it issues an error message.这篇关于bash错误使用空格重命名文件 - mv目标不是一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!