[英]How to replace underscores in filename with spaces while copying to a directory in unix
I want to copy a file (containing underscores in its name) to a directory where I want to replace underscores with spaces in the filename.我想将一个文件(名称中包含下划线)复制到一个目录中,我想用文件名中的空格替换下划线。
cp -pr myDir/myFile_With_Underscore.pdf my2Dir
I want to put filename with replacing underscore with spaces in my2Dir.我想用 my2Dir 中的空格替换下划线来放置文件名。
Like myFile_With_Underscore.pdf should be myFile With Underscore.pdf in my2Dir.像myFile_With_Underscore.pdf应该是my2Dir中的myFile With Underscore.pdf。
you could use the tr
command (see: man tr
):您可以使用
tr
命令(请参阅: man tr
):
cp "/path/to/${source}" "/new/path/to/$(echo ${source} | tr '_' ' ')"
tr
will translate one set of chars to another, thus replacing every _
with a space. tr
会将一组字符转换为另一组字符,从而用空格替换每个_
。
One very important note: Do not forget to quote the copy parameters when containing spaces.一个非常重要的注意事项:不要忘记在包含空格时引用复制参数。 Without quotes every word would be considered a seperate character.
如果没有引号,每个单词都将被视为一个单独的字符。 So:
所以:
cp my_file my new file # NOT OK
cp my_file "my_new_file" # OK, as the parameter with spaces is quoted
cp "my_file" "my new file" # Also OK. Quotes on the first not neccessary, but dont hurt either
As tr
will do, you could also do this with several other commands such as sed
or awk
.正如
tr
所做的那样,您也可以使用其他几个命令(例如sed
或awk
执行此操作。 For example using sed
:例如使用
sed
:
cp "/path/to/${source}" "/new/path/to/$(echo ${source} | sed 's/\_/ /g')"
But I would recommand sticking to tr
with such easy tasks.但我会建议坚持使用
tr
完成如此简单的任务。
You can use rename
for this, to change all PDF files in the current directory, do您可以为此使用
rename
,以更改当前目录中的所有 PDF 文件,请执行
rename 'y/_/ /' *.pdf
In your concrete example do:在您的具体示例中,请执行以下操作:
cp -p myDir/myFile_With_Underscore.pdf my2Dir && rename 'y/_/ /' my2Dir/myFile_With_Underscore.pdf
What about something like this:这样的事情怎么样:
for i in myDir/myFile_With_Underscore.pdf; do \
cp $i myDir2/${$(basename $i)//_/ }; done
If you were in the same directory where the origin file is located you could omit the basename
, for example:如果您位于原始文件所在的同一目录中,则可以省略
basename
,例如:
for i in .myFile_With_Underscore.pdf; do cp $i ../myDir2/${i//_/ }; done
Notice the ${i//_/ }
, in order to manipulate the name of the file, the name needs to be in the variable $i
therefore the use of the for i in
注意
${i//_/ }
,为了操作文件的名称,名称需要在变量$i
因此使用for i in
${string//substring/replacement} Replace all matches of $substring with $replacement . ${string//substring/replacement}用$replacement 替换$substring 的所有匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.