简体   繁体   中英

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:

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.

Then, you can loop through all your files and use mv command to rename the files.

Using the perl rename (sometimes called prename ) utility:

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 .)

How it works

rename takes a perl commands as an argument. 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. 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| . In our case, old is ada/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 . This creates the new file name using the two captured groups.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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