Linux cp with a regexp

拈花ヽ惹草 提交于 2019-12-04 13:04:57

问题


I would like to copy some files in a directory, renaming the files but conserving extension. Is this possible with a simple cp, using regex ?

For example :

cp ^myfile\.(.*) mydir/newname.$1

So I could copy the file conserving the extension but renaming it. Is there a way to get matched elements in the cp regex to use it in the command ? If not, I'll do a perl script I think, or if you have another way...

Thanks


回答1:


Suppose you have myfile.a, myfile.b, myfile.c:

for i in myfile.*; do echo mv "$i" "${i/myfile./newname.}"; done

This creates (upon removal of echo) newname.a, newname.b, newname.c.




回答2:


The shell doesn't understand general regexes; you'll have to outsource to auxiliary programs for that. The classical scripty way to solve your task would be something like

for a in myfile.* ; do
  b=`echo $a | sed 's!^myfile!mydir/newname!'`
  cp $a $b
done

Or have a perl script generate a list of commands that you then source into the shell.




回答3:


I really like the regex syntax of the rename perl script (by Robin Barker and Larry Wall), e.g.:

rename "s/OldFile/NewFile/" OldFile*

OldFile.c and OldFile.h are renamed to NewFile.c and NewFile.h, respectively

I simply wanted the exact same thing with a copy command:

copy "s/OldFile/NewFile/" OldFile*

So I duplicated that script and changed the rename statement to copy via File::Copy. Et voila! A copy command with perl-regex syntax:

https://gist.github.com/jcward/0ead33bd79f2061c68728cc82582241f



来源:https://stackoverflow.com/questions/7135324/linux-cp-with-a-regexp

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