带有正则表达式的 Linux cp

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7135324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 05:48:51  来源:igfitidea点击:

Linux cp with a regexp

regexlinuxcp

提问by Johy

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 ?

我想复制目录中的一些文件,重命名文件但保留扩展名。cp使用正则表达式可以做到这一点吗?

For example :

例如 :

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

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

所以我可以复制保存扩展名但重命名的文件。有没有办法在cp正则表达式中获取匹配的元素以在命令中使用它?如果没有,我会做一个我认为的 perl 脚本,或者如果你有另一种方式......

Thanks

谢谢

采纳答案by Kerrek SB

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

假设你有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.

这将创建(删除echonewname.anewname.bnewname.c

回答by hmakholm left over Monica

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

shell 不理解一般的正则表达式;您必须为此外包给辅助程序。解决您的任务的经典脚本方法类似于

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.

或者让 perl 脚本生成一个命令列表,然后将这些命令输入到 shell 中。

回答by Jeff Ward

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

我真的很喜欢renameperl 脚本的正则表达式语法(由 Robin Barker 和 Larry Wall 编写),例如:

rename "s/OldFile/NewFile/" OldFile*

OldFile.cand OldFile.hare renamed to NewFile.cand NewFile.h, respectively

rename "s/OldFile/NewFile/" OldFile*

OldFile.cOldFile.h重命名为NewFile.cNewFile.h分别,

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

我只是想要一个复制命令完全相同的东西:

copy "s/OldFile/NewFile/" OldFile*

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:

因此,我复制了该脚本并将重命名语句更改为通过File::Copy. 等等!带有 perl-regex 语法的复制命令:

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

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