Rename multiple files with regular expression

2019-06-13 02:01发布

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

2条回答
地球回转人心会变
2楼-- · 2019-06-13 02:36

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.

查看更多
混吃等死
3楼-- · 2019-06-13 02:51

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
查看更多
登录 后发表回答