使用 mv 在 bash 中使用正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41214552/
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
Use of regex in bash with mv
提问by Erik Apostol
I have 4 files to rename:
我有 4 个文件要重命名:
./01:
I0010001 I0020001
./02:
I0010001 I0020001
I want to add auxiliary filename .dcm
to each file, so I have tried:
我想为.dcm
每个文件添加辅助文件名,所以我尝试过:
$ mv \(*/*\) .dcm
mv: cannot stat '(*/*)': No such file or directory
$ mv \(./*/*\) .dcm
mv: cannot stat '(./*/*)': No such file or directory
$ mv \(./\*/\*\) .dcm
mv: cannot stat '(./*/*)': No such file or directory
$ mv "\(./*/*\)" ".dcm"
mv: cannot stat '\(./*/*\)': No such file or directory
$ mv 0\([1-2]\)/I00\([1-2\)]0001 0/I00001.dcm
mv: cannot stat '0([1-2])/I00([1-2)]0001': No such file or directory
$ mv "0\([1-2]\)/I00\([1-2\)]0001" "0/I00001.dcm"
mv: cannot stat '0\([1-2]\)/I00\([1-2\)]0001': No such file or directory
$ mv "0\([1-2]\)/I00\([1-2]\)0001" "0/I00001.dcm"
mv: cannot stat '0\([1-2]\)/I00\([1-2]\)0001': No such file or directory
$ mv "0\([[:digit:]]\)/I00\([[:digit:]]\)0001" "0/I00001.dcm"
mv: cannot stat '0\([[:digit:]]\)/I00\([[:digit:]]\)0001': No such file or directory
$ mv "0\([1-2]\)\/I00\([1-2]\)0001" "0/I00001.dcm"
mv: cannot stat '0\([1-2]\)\/I00\([1-2]\)0001': No such file or directory
$ mv \(*\) .dcm
mv: cannot stat '(*)': No such file or directory
None of them yield the result I want.
他们都没有产生我想要的结果。
采纳答案by paxdiablo
You don't really need regular expressions here, this is very simple with a for
loop:
你真的不需要这里的正则表达式,这是一个非常简单的for
循环:
for f in 0[12]/I00[12]0001 ; do mv "$f" "${f}.dcm" ; done
For more complex situations, you should be looking into the rename
program (prename
on some systems), which uses powerful Perl regular expressions to handle the renaming. Though unnecessary here, this simple case would use:
对于更复杂的情况,您应该查看rename
程序(prename
在某些系统上),它使用强大的 Perl 正则表达式来处理重命名。虽然这里没有必要,但这个简单的案例将使用:
pax> rename -n 's/$/.dcm/' 0[12]/I00[12]0001
rename(I01/I0010001, I01/I0010001.dcm)
rename(I01/I0020001, I01/I0020001.dcm)
rename(I02/I0010001, I02/I0010001.dcm)
rename(I02/I0020001, I02/I0020001.dcm)
That -n
is debug mode (print what would happen but don't actuallyrename). Remove it once you're happy it will do what you want.
那-n
是调试模式(打印会发生什么但实际上不重命名)。一旦您感到满意,就将其删除,它会做您想做的事。