Renaming files using regular expressions - Linux

浪子不回头ぞ 提交于 2019-12-13 17:39:33

问题


I have three files named

file1.txt
file2.txt
file3.txt

I am trying to rename them to

mynewfile-1.txt
mynewfile-2.txt
mynewfile-3.txt

How would I go about this using regular expressions?


回答1:


Try this :

rename -n 's/^file/mynewfile-/' *.txt

or from comments :

rename -n 's/^file(\d+)/mynewfile-${1}-test/' *.txt
                   ___            ____
                    ^               ^
              capturing group       |
                               captured group

(remove -n switch when your tests are OK)

There are other tools with the same name which may or may not be able to do this, so be careful.

If you run the following command (GNU)

$ file "$(readlink -f "$(type -p rename)")"

and you have a result like

.../rename: Perl script, ASCII text executable

and not containing:

ELF

then this seems to be the right tool =)

If not, to make it the default (usually already the case) on Debian and derivative like Ubuntu :

$ sudo update-alternatives --set rename /path/to/rename

(replace /path/to/rename to the path of your perl's rename command.


If you don't have this command, search your package manager to install it or do it manually (no deps)


Last but not least, this tool was originally written by Larry Wall, the Perl's dad.



来源:https://stackoverflow.com/questions/49267913/renaming-files-using-regular-expressions-linux

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