Rename multiple files with regular expression

不想你离开。 提交于 2019-12-23 05:14:07

问题


I downloaded some files from internet. In the name field of those files each ' ' character is replaced by "%20". I want to rename all of those but number of files is too high. So manual approach would be clumsy. I know from command line with regular expression this can be done but I am not very familiar with it. So little help is needed.

Summary is, I want to rename all files in a directory by replacing all "%20" patterns with " ". How can I do it?

Sample:

17%20Clipping.cpp --> 17 Clipping.cpp
14%20Mouse%20(Button)%20Listener.cpp --> 14 Mouse (Button) Listener.cpp

回答1:


you can rename a group of files using command rename that accept regular expression

For example, to rename all files matching "*.bak" to strip the extension, you might say

rename 's/\.bak$//' *.bak

To translate uppercase names to lower, you'd use

rename 'y/A-Z/a-z/' *

and your answer:

rename 's/%20/ /' *.cpp



回答2:


I would recommend against putting spaces in filenames (maybe use underscore instead). Regardless, here is a command that will do it:

for i in *%20*; do new=$(echo $i|sed 's/%20/ /'); echo mv $i "$new"; done

In its current form it merely prints the commands it would execute. Once you're sure it does what you want, remove the echo.

As @ronmrdechai suggests, the following is an improvement:

for i in *%20*; do echo mv $i "${i/\%20/ }"; done

The backslash is needed in the pattern because % is a metacharacter (match at end) in this case.



来源:https://stackoverflow.com/questions/20251042/rename-multiple-files-with-regular-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!