简体   繁体   English

用于重命名和重新排列文件的脚本shell

[英]Script shell for renaming and rearranging files

I would like to rearrange and rename files. 我想重新排列和重命名文件。 I have this tree structure of files : 我有这种文件树结构:

ada/rda/0.05/alpha1_freeSurface.md
ada/rda/0.05/p_freeSurface.md
ada/rda/0.05/U_freeSurface.md
ada/rda/0.1/alpha1_freeSurface.md
ada/rda/0.1/p_freeSurface.md
ada/rda/0.1/U_freeSurface.md

I want that files will be renamed and rearranged like this structure below: 我想要重命名和重新排列文件,如下面的结构:

ada/rda/ada-0.05-alpha1.md
ada/rda/ada-0.05-p.md
ada/rda/ada-0.05-U.md
ada/rda/ada-0.1-alpha1.md
ada/rda/ada-0.1-p.md
ada/rda/ada-0.1-U.md

You can use basename and dirname functions to reconstruct the new filename: 您可以使用basenamedirname函数重建新文件名:

get_new_name()
{
    oldname=$1
    prefix=$(basename $oldname _freeSurface.md)
    dname=$(dirname $oldname)
    basedir=$(dirname $dname)
    dname=$(basename $dname)
    echo "$basedir/ada-$dname-$prefix.md"
}

eg get_new_name("ada/rda/0.05/alpha1_freeSurface.md") will show ada/rda/ada-0.05-alpha1.md in console. 例如, get_new_name("ada/rda/0.05/alpha1_freeSurface.md")将在控制台中显示ada/rda/ada-0.05-alpha1.md

Then, you can loop through all your files and use mv command to rename the files. 然后,您可以遍历所有文件并使用mv命令重命名文件。

Using the perl rename (sometimes called prename ) utility: 使用perl rename (有时称为prename )实用程序:

rename  's|ada/rda/([^/]*)/([^_]*).*|ada/rda/ada-$1-$2.md|' ada/rda/*/*

(Note: by default, some distributions install a rename command from the util-linux package. This command is incompatible . If you have such a distribution, see if the perl version is available under the name prename .) (注意:默认情况下,某些发行版会从util-linux软件包安装一个rename命令。此命令不兼容 。如果您有这样的发行版,请查看perl版本是否在名称prename下可用。)

How it works 这个怎么运作

rename takes a perl commands as an argument. rename将perl命令作为参数。 Here the argument consists of a single substitute command. 这里的参数由一个替换命令组成。 The new name for the file is found from applying the substitute command to the old name. 通过将substitute命令应用于旧名称,可以找到该文件的新名称。 This allows us not only to give the file a new name but also a new directory as above. 这使我们不仅可以为文件指定新名称,还可以为上面的新目录。

In more detail, the substitute command looks like s|old|new| 更详细地说,substitute命令看起来像s|old|new| . In our case, old is ada/rda/([^/]*)/([^_]*).* . 在我们的例子中, oldada/rda/([^/]*)/([^_]*).* This captures the number in group 1 and the beginning of the filename (the part before the first _ ) in group 2. The new part is ada/rda/ada-$1-$2.md . 这将捕获组2中的数字和组2中文件名的开头(第一个_之前的部分)。 new部分是ada/rda/ada-$1-$2.md This creates the new file name using the two captured groups. 这将使用两个捕获的组创建新文件名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM