使用bash脚本更改文件名:通过下划线替换逗号和空格
我的文件是格式,
Country, City S1.txt
例如
USA, Los Angeles S1.txt
USA, San Francisco S3.txt
UK, Glouchester S4.txt
Argentina, Buenos Aires S7.txt
我希望将它们更改为
Country_City_S1.txt
例如
USA_Los_Angeles_S1.txt
USA_San_Franciso_S3.txt
UK_Glouchester_S4.txt
Argentina_Buenos_Aires_S7.txt
要删除逗号,我使用以下sed命令:
sed -i 's/,//g'
用下划线替换空格,我使用以下sed命令:
sed -i 's/ /_/g'
问题:有没有办法将上述两个命令组合到一个命令中?还是可以完成以上操作的整洁方法?
注意:
我更改了原始帖子的标题,以更好地反映我需要做的事情。对此我的混乱感到抱歉。
我现在了解我需要的东西,这是一个bash脚本,而不是更改文件名的 sed 。
我感谢所有已提出建议的 sed 命令的人。
我更喜欢在bash脚本中使用 mv 命令 *对于 .txt中的f;做MV .......;完成
My files are of the format
Country, City S1.txt
e.g.
USA, Los Angeles S1.txt
USA, San Francisco S3.txt
UK, Glouchester S4.txt
Argentina, Buenos Aires S7.txt
I wish to change them to
Country_City_S1.txt
e.g.
USA_Los_Angeles_S1.txt
USA_San_Franciso_S3.txt
UK_Glouchester_S4.txt
Argentina_Buenos_Aires_S7.txt
To remove the comma I use the following sed command:
sed -i 's/,//g'
To replace the whitespaces with underscore, I use the following sed command:
sed -i 's/ /_/g'
Question: Is there a way to combine the above two commands into one? Or is there a neater way to accomplish the above?
Notes:
I have changed the title of my original post to better reflect what I need to be done. I am sorry for any confusion caused as a result of the change.
I understand now what I need, which is a bash script and not sed to change filenames.
I thank all those who have replied with their suggested sed commands.
I prefer to use the mv command in a bash script as in for example
*for f in .txt; do mv .......; done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
用单个下划线替换空间和逗号的任何组合:
请参见实时演示。
在上使用此正则命名的文件重命名文件,任何 *nix OS(MacOS不使用
重命名
):如果您的 *nix具有
Rename
命令(brew install inname
如果您是macos):Replace any combination of spaces and commas with a single underscore:
See live demo.
To rename files using this regex on any *nix OS (macos doesn't ship with
rename
):If your *nix has the
rename
command (brew install rename
if you're macos):合并您的两个
sed
表达式:Merge your two
sed
expressions:这可能对您有用(GNU SED):
删除逗号并将空间转换为下划线。
也许是:
重命名文件名:也许:
This might work for you (GNU sed):
Remove commas and translate spaces to underscores.
Or perhaps:
To rename file names, perhaps:
这里的一行解决方案:
这是一个非常有用的命令模板,用于重命名文件:
One line solution here:
This is a very useful command template for batch renaming files: