我想通过用下划线替换所有包含空格的pdf文件。 所以我调用命令:
ls *.pdf | sed -e 'p; s/" "/_/' | xargs -n2 mv
我在终端上遇到错误:
mv: cannot stat ‘Beginning’: No such file or directory
mv: cannot stat ‘Linux’: No such file or directory
mv: cannot stat ‘Line.pdf’: No such file or directory
mv: cannot stat ‘The’: No such file or directory
mv: cannot stat ‘Command’: No such file or directory
mv: cannot stat ‘Head’: No such file or directory
mv: cannot stat ‘C.pdf’: No such file or directory
mv: cannot stat ‘First’: No such file or directory
mv: cannot stat ‘Head’: No such file or directory
mv: cannot stat ‘PHP’: No such file or directory
mv: cannot stat ‘MySQL.pdf’: No such file or directory
mv: cannot stat ‘First’: No such file or directory
mv: cannot stat ‘and’: No such file or directory
mv: cannot stat ‘Linux’: No such file or directory
mv: cannot stat ‘Guide.pdf’: No such file or directory
mv: cannot stat ‘Pocket’: No such file or directory
mv: cannot stat ‘The’: No such file or directory
mv: cannot stat ‘C.pdf’: No such file or directory
mv: cannot stat ‘ANSI’: No such file or directory
mv: cannot stat ‘The’: No such file or directory
mv: cannot stat ‘Command’: No such file or directory
mv: cannot stat ‘The’: No such file or directory
mv: cannot stat ‘Command’: No such file or directory
mv: cannot stat ‘The’: No such file or directory
mv: cannot stat ‘Programming’: No such file or directory
mv: cannot stat ‘The’: No such file or directory
mv: cannot stat ‘Programming’: No such file or directory
那么命令有什么问题?
答案 0 :(得分:4)
获取基于Perl的rename
命令(有时称为prename
)来完成这项工作:
prename 's/ /_/g' *.pdf
shell globbing将每个文件名分开; prename
命令执行批量重命名; s/ /_/g
操作将文件名中的每个空格替换为_
。 (原始代码仅用下划线替换第一个空白,然后在空格(空格和制表符以及换行符)上违反xargs
错误。
答案 1 :(得分:2)
您可以尝试引用文件名:
ls *.pdf | sed -e 's/.*/"&"/; p; s/ /_/g' | xargs -n2 mv
这可能也是你手工操作的方式:
mv "File with spaces" "File_with_spaces"
依靠纯粹的bash,你必须使用for-loop和bash替换:
for file in $(ls *.pdf); do echo "$file" "${file// /_}"; done
答案 2 :(得分:1)
首先,您的sed
命令与任何文件都不匹配,因为您尝试匹配quote-space-quote
而不仅仅是space
。除非您的文件名为A" "file.pdf
,否则您将无法与sed
匹配。
我们假设您已将其修复为sed -e 'p; 's/ /_/g'
。如果您有一个名为A file.pdf
的文件,则输出将为
A file.pdf
A_file.pdf
并将这些作为参数传递给xargs
。但是,xargs
被指示采用前两个参数。在这种情况下,它们将是A
和file.pdf
,两者都不存在,因此mv
无法统计它们!
在我看来,这是一种更简单的方法:
for file in *.pdf; do mv "$file" "$(echo $file | sed 's/ /_/g')"; done