Reputation: 67
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
Upvotes: 4
Views: 144
Reputation: 113844
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
.)
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.
Upvotes: 1
Reputation: 46688
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"
}
e.g. 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.
Upvotes: 1