首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在包含空格的Linux中批量重命名文件?

如何在包含空格的Linux中批量重命名文件?
EN

Stack Overflow用户
提问于 2014-05-26 06:38:23
回答 3查看 6.9K关注 0票数 1

我想重命名所有包含空格的pdf文件,用下划线代替它们。因此,我调用命令:

代码语言:javascript
复制
ls *.pdf | sed -e 'p; s/" "/_/' | xargs -n2 mv

我在终端上发现了错误:

代码语言:javascript
复制
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

那么这个命令有什么问题呢?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-05-26 06:59:19

获取基于Perl的rename命令(有时称为prename)来完成以下工作:

代码语言:javascript
复制
prename 's/ /_/g' *.pdf

shell全局化使每个文件名保持独立;prename命令进行批量重命名;s/ /_/g操作将每个空白替换为文件名中的任何位置的_。(原始代码只用下划线替换第一个空白,然后在空白(空格和制表符以及换行符)上运行xargs中断。)

票数 4
EN

Stack Overflow用户

发布于 2014-05-26 06:44:43

首先,您的sed命令不匹配任何文件,因为您试图匹配的是quote-space-quote而不是space。除非您有一个名为A" "file.pdf的文件,否则您将无法将其与sed匹配。

假设您已将其修复为sed -e 'p; 's/ /_/g'。如果您有一个名为A file.pdf的文件,您的输出将是

代码语言:javascript
复制
A file.pdf
A_file.pdf

将这些参数作为参数传递给xargs。然而,xargs被指示接受前两个参数。在这种情况下,它们将是Afile.pdf,两者都不存在,因此mv无法对它们进行统计!

在我看来,下面是一种更容易做到的方法:

代码语言:javascript
复制
for file in *.pdf; do mv "$file" "$(echo $file | sed 's/ /_/g')"; done
票数 3
EN

Stack Overflow用户

发布于 2014-05-26 06:52:05

您可以尝试引用文件名:

代码语言:javascript
复制
ls *.pdf | sed -e 's/.*/"&"/; p; s/ /_/g' | xargs -n2 mv

这可能也是你用手做的:

代码语言:javascript
复制
mv "File with spaces" "File_with_spaces"

依赖于纯bash,您必须使用for-循环和bash替换:

代码语言:javascript
复制
for file in $(ls *.pdf); do echo "$file" "${file// /_}"; done
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23864135

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档