简体   繁体   English

使用Shell脚本时,如何复制名称包含空格和UNICODE的文件?

[英]How can I copy files with names containing spaces and UNICODE, when using a shell script?

I have a list of files that I'm trying to copy and move (using cp and mv) in a bash shell script. 我有一个要在bash shell脚本中复制和移动(使用cp和mv)的文件列表。 The problem that I'm running into, is that I can't get either command to recognize a huge number of files, seemingly because the filenames contain spaces and/or unicode characters. 我遇到的问题是,我似乎无法获得任何命令来识别大量文件,这似乎是因为文件名包含空格和/或Unicode字符。 I couldn't find any switches to decode/re-encode these characters. 我找不到任何开关来解码/重新编码这些字符。 Instead, for example, if I copy "file name.xml", I get "*.xml" and a script error that the file wasn't found for my result. 相反,例如,如果我复制“ file name.xml”,则会得到“ * .xml”和一个脚本错误,即找不到用于结果的文件。 Does anyone know settings or commands that will deal with these files? 有谁知道将处理这些文件的设置或命令?

EDIT(adding current code): When I run: 编辑(添加当前代码):运行时:

MacBookPro:Desktop$ ./script.sh MacBookPro:台式机$ ./script.sh

#!/bin/sh
dateVar=`date +%Y-%m-%d`
mkdir /Volumes/Documents/SMSarchive/$dateVar
cd /Volumes/Documents/SMSarchive/SMSdrop
for i in *.xml
do
cp $i /Volumes/Documents/SMSarchive/$dateVar/$dateVar-$i
done

I get the message: 我收到消息:

usage: cp [-R [-H | 用法:cp [-R [-H | -L | -L | -P]] [-fi | -P]] [-fi | -n] [-pvX] source_file target_file cp [-R [-H | -n] [-pvX]源文件目标文件cp [-R [-H | -L | -L | -P]] [-fi | -P]] [-fi | -n] [-pvX] source_file ... target_directory -n] [-pvX]源文件...目标目录

...when it hits the "cp" command. ...点击“ cp”命令时。 There's actually more to the script, that processes the copied files further. 实际上,脚本还有更多功能,可以进一步处理复制的文件。 With a "regular" file name eg 'file.xml', everything works fine. 使用“常规”文件名,例如“ file.xml”,一切正常。 It's only files with spaces, or Unicode characters, where I have problems. 这只是我遇到问题的带有空格或Unicode字符的文件。

Problems with spaces indicates that insufficient quoting has been done. 空格问题表明报价不足。 The following is incorrect: 以下是不正确的:

someprogram $file

The correct version is as follows: 正确的版本如下:

someprogram "$file"

watch out for code errors when $i is null! 当$ i为空时要小心代码错误! This can be the result of fatal rm -Rf errors! 这可能是致命的rm -Rf错误的结果!

Sometimes there are easier ways than dealing with shell quoting. 有时候,有比处理shell引用更简单的方法。 In your case I would use find -print0 and xargs -0 . 在您的情况下,我将使用find -print0xargs -0 The null character termination allows you to easily manipulate strings with spaces (ie lists of filenames). 空字符终止使您可以轻松地使用空格(即文件名列表)操作字符串。

For your example, code would look something like this: 对于您的示例,代码将如下所示:

#!/bin/sh
dateVar=`date +%Y-%m-%d`
mkdir /Volumes/Documents/SMSarchive/$dateVar
cd /Volumes/Documents/SMSarchive/SMSdrop
find . -maxdepth 1 -name '*.xml' -print0 | \
xargs -0 -I {} cp {} /Volumes/Documents/SMSarchive/$dateVar/$dateVar-{}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM