使用正则表达式搜索并将linux上的重命名替换为目录创建

时间:2015-05-13 01:17:56

标签: regex linux replace rename mkdir

获取文件列表,例如:

/home/me/specialfiles/group01subgroup01.xyz
/home/me/specialfiles/group01subgroup01.abc
/home/me/specialfiles/group01subgroup01.nop
/home/me/specialfiles/group01subgroup02.xyz
/home/me/specialfiles/group01subgroup02.abc
/home/me/specialfiles/group01subgroup02.nop
/home/me/specialfiles/group01subgroup03.xyz
/home/me/specialfiles/group01subgroup03.abc
/home/me/specialfiles/group01subgroup03.nop
/home/me/specialfiles/group01subgroup04.xyz
/home/me/specialfiles/group01subgroup04.abc
/home/me/specialfiles/group01subgroup04.nop

我想重命名这些文件并添加一些与此类似的格式:

me@mymachine:~/specialfiles$ rename 's/group(\d\d)subgroup(\d\d)\.(xyz|abc|nop)/Group$1SubGroup$2.$3/' *

这最终会得到类似

的文件列表
/home/me/specialfiles/Group01SubGroup01.xyz
/home/me/specialfiles/Group01SubGroup01.abc
/home/me/specialfiles/Group01SubGroup01.nop
/home/me/specialfiles/Group01SubGroup02.xyz
/home/me/specialfiles/Group01SubGroup02.abc
/home/me/specialfiles/Group01SubGroup02.nop
/home/me/specialfiles/Group01SubGroup03.xyz
/home/me/specialfiles/Group01SubGroup03.abc
/home/me/specialfiles/Group01SubGroup03.nop
/home/me/specialfiles/Group01SubGroup04.xyz
/home/me/specialfiles/Group01SubGroup04.abc
/home/me/specialfiles/Group01SubGroup04.nop

到目前为止,一切正常。下一步,我的真正问题是,如何使用目录的子组名称为此过程中的每个子组创建目录?

例如,我的第一个猜测就是做这样的事情

me@mymachine:~/specialfiles$ rename 's/group(\d\d)subgroup(\d\d)\.(xyz|abc|nop)/Group$1SubGroup$2\/Group$1SubGroup$2.$3/' *

这样做的目的是将文件重命名为类似这样的文件

/home/me/specialfiles/Group01SubGroup01/Group01SubGroup01.xyz
/home/me/specialfiles/Group01SubGroup01/Group01SubGroup01.abc
/home/me/specialfiles/Group01SubGroup01/Group01SubGroup01.nop
/home/me/specialfiles/Group01SubGroup02/Group01SubGroup02.xyz
/home/me/specialfiles/Group01SubGroup02/Group01SubGroup02.abc
/home/me/specialfiles/Group01SubGroup02/Group01SubGroup02.nop
/home/me/specialfiles/Group01SubGroup03/Group01SubGroup03.xyz
/home/me/specialfiles/Group01SubGroup03/Group01SubGroup03.abc
/home/me/specialfiles/Group01SubGroup03/Group01SubGroup03.nop
/home/me/specialfiles/Group01SubGroup04/Group01SubGroup04.xyz
/home/me/specialfiles/Group01SubGroup04/Group01SubGroup04.abc
/home/me/specialfiles/Group01SubGroup04/Group01SubGroup04.nop

但是,我最终得到了一条消息,如

Can't rename Group01SubGroup01.xyz Group01SubGroup01/Group01SubGroup01.xyz: No such file or directory

似乎问题是目录Group01SubGroup01需要已经存在才能成功完成。关于如何以某种方式使用正则表达式搜索并替换语法来创建目录(如果它们不存在)的任何想法?

1 个答案:

答案 0 :(得分:1)

cd /home/me/specialfiles/
find ./ -maxdepth 1 -name "Group*" | xargs -i basename {} | while read filename; do  _dir=${filename%.*}; mkdir -p $_dir; mv $filename $_dir;  done