ReNamer:Pascal Script:SplitPath

From den4b Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
{{{iparam}}} This article needs to be cleaned up!

Find an overview of all build-in functions there >> File Name Utilities.


Here on this page we show you only the needed functions to extract parts
of the file name and how to use them in an PascalScript for ReNamer.


We like to show you this on an example file name
"C:\GreatGrand\GrandParent\ParentFolder\file.ext"


First, there are the always available variables 'FilePath' and 'FileName'
You don't have to declare ('var' / 'dim') or initialize ('var="";') this variables.
Just use them, they are always there for you.

Variable provides
FilePath C:\GreatGrand\GrandParent\ParentFolder\file.ext
FileName file.ext

Use this e.g. like:

var 
  vExt: WideString;
begin 
  vExt     := WideExtractFileExt(FilePath);
  FileName := FileName + '.backup' + vExt;
end.



And there are this functions to extract parts:

Function provides
WideExtractFilePath C:\GreatGrand\GrandParent\ParentFolder\
WideExtractFileDir C:\GreatGrand\GrandParent\ParentFolder
WideExtractFileDrive C:\
WideExtractFileName file.ext
WideExtractBaseName file
WideExtractFileExt .ext (dot included)


You can fill an variable with the extracted part first
Use this e.g. like:

var 
  vPath, vDir, vDrive, vName, vBase, vExt, vE: WideString;
  vOUT: WideString; 
begin
 
  //extract the parts and store them into an var each:
  vPath  := WideExtractFilePath(FilePath);
  vDir   := WideExtractFileDir(FilePath);
  vDrive := WideExtractFileDrive(FilePath);
  vName  := WideExtractFileName(FilePath);
  vBase  := WideExtractBaseName(FilePath);
  vExt   := WideExtractFileExt(FilePath);

  // Test output as MsgBox:
  vOUT  := 'Default build-in vars:'             + #13#10
        + 'FilePath >>> '            + FilePath + #13#10
        + 'FileName >>> '            + FileName + #13#10
        +  #13#10
        + 'Extracted by using functions:'       + #13#10
        + 'WideExtractFilePath  >>> ' + vPath   + #13#10
        + 'WideExtractFileDir   >>> ' + vDir    + #13#10
        + 'WideExtractFileDrive >>> ' + vDrive  + #13#10
        + 'WideExtractFileName  >>> ' + vName   + #13#10
        + 'WideExtractBaseName  >>> ' + vBase   + #13#10
        + 'WideExtractFileExt   >>> ' + vExt;
       ShowMessage( vOUT );
end.

Or just use the function 'on the fly', without using an var first
Use this e.g. like:

begin 
  FileName := FileName + '_backup' + WideExtractFileExt(FilePath);
end.





But this functions didn't gave all possibilities to split an full path into all wanted parts.
You have to know how to handle this functions and/or use own code to achieve what you want.

Here are some code snippets for this issue:

First we show you an 'trick' seen by Denis:
Here we extract the path first "WideExtractFileDir(FilePath)"
and then extract the last part, which is normal the filename, but here the parent folder "WideExtractFileName(...)"

You can even use this trick more then once:

(Here for our example "C:\GreatGrand\GrandParent\ParentFolder\file.ext")

nested Functions provides the folder
WideExtractFileName(WideExtractFileDir(FilePath)); ParentFolder
WideExtractFileName(WideExtractFileDir(WideExtractFileDir(FilePath))); GrandParent
WideExtractFileName(WideExtractFileDir(WideExtractFileDir(WideExtractFileDir(FilePath)))); GreatGrand


Use this like:

var 
  ParentFolder, GrandParent, GreatGrandParent: WideString;
begin 
  ParentFolder     := WideExtractFileName(WideExtractFileDir(FilePath));
  GrandParent      := WideExtractFileName(WideExtractFileDir(WideExtractFileDir(FilePath)));
  GreatGrandParent := WideExtractFileName(WideExtractFileDir(WideExtractFileDir(WideExtractFileDir(FilePath))));
  FileName         := GreatGrandParent + '-' + GrandParent + '-' + ParentFolder + '-' + FileName;
end.



Other tricks:

To get the extension without the dot use something like:

 vExt := WideReplaceStr(WideExtractFileExt(FilePath), '.', '');

Or showing this as step by step:

  vExt   := WideExtractFileExt(FilePath);
  vExt   := WideReplaceStr( vExt, '.', '');




Here is an another way to get the name of an parent folder of an path
by splitting the path at the back slash into an array of 'Folders'.

We use
Folders: TWideStringArray;
"Folders := WideSplitString( WideExtractFileDir(FilePath), at sign '\')"

to get the elements of such an path.
Then we can access each level of parent folders
by referring to the right element in the array.
Note that an array start counting at '0'
And if you try to access an array element that is not there,
you will get an error message "Exception: Out Of Range".

Again for our example "C:\GreatGrand\GrandParent\ParentFolder\file.ext"
there are 4 elements in the array, counting from '0' to '3'

Array level provides
Folders[0] C:
Folders[1] GreatGrand
Folders[2] GrandParent
Folders[3] ParentFolder

If you not know how deep the folder hierarchy is, you may want to count from the right.
Therefor we can utilize the max. amount of elements in an array. We use the 'Length' attribute here.
"Length(Folders)" is '4'. But Folders[4] is for our example path "Out Of Range".
That is why we use "Length(Folders) -1" to get '3'.
So to get the last element in array use "Folders[ Length(Folders) -1 ]", which is here the same as "Folders[ 3 ]"
And so we can use '-1' (4 -1 = 3) till '-4' (4 -4 = 0) for our example path. (remember: we have 4 elements, from '0' to '3'.)

Array level provides the folder
Folders[Length(Folders)-1] ParentFolder
Folders[Length(Folders)-2] GrandParent
Folders[Length(Folders)-3] GreatGrand
Folders[Length(Folders)-4] C:


Use this like:

var 
  Folders: TWideStringArray; 
  oldPath, ParentFolder, GrandParentFolder, GrandGrandParentFolder, TopMostFolder, SecondTopMostFolder: WideString;

begin 
    // Get parts of the current file path:
  oldPath                := WideExtractFileDir(FilePath);
  Folders                := WideSplitString(oldPath, '\'); 
  TopMostFolder          := Folders[1];
  SecondTopMostFolder    := Folders[2];
  GrandGrandParentFolder := Folders[Length(Folders)-3];
  GrandParentFolder      := Folders[Length(Folders)-2];
  ParentFolder           := Folders[Length(Folders)-1];

  FileName := SecondTopMostFolder + '-' + GrandParentFolder + '-' + ParentFolder + '-' + FileName;
end.

Tip:
You can use ShowMessage() like MsgBox to be prompte what the elements contains:

ShowMessage('Debug: ' + Folders[1] + ' # ' + Folders[Length(Folders)-1] );

To loop trough each element of an part (e.g. to check if an given folder exists)
you may take an look at this example:

var
  I: Integer;  Parts: TWideStringArray;
begin
//function WideSplitString(const Input, Delimiter: WideString): TWideStringArray;
  Parts := WideSplitString(FilePath, '\');
  for I:=0 to Length(Parts)-1 do
  begin
    // access each part via Parts[i]
  end;
end.




And you could use Regular Expression to extract the parts of an part:

  Parent       := ReplaceRegEx(FilePath, '.+\\(.+)\\.+',         '$1', False, True);
  GrandPa      := ReplaceRegEx(FilePath, '.+\\(.+)\\.+\\.+',     '$1', False, True);
  GrandGrandPa := ReplaceRegEx(FilePath, '.+\\(.+)\\.+\\.+\\.+', '$1', False, True);

But note that RegEx is slow by its nature. But then you will see this first for more then thousand files ;-)




You can also use Meta Tags to extract e.g. the parent folder:

ParentFolder := CalculateMetaTag(FilePath, ':File_FolderName:');

See 'Insert' Rule and click there at 'Insert Meta Tag'




File name

To split the file name
into parts at an given delimiter
we can use f.ex.:

E.g. for
FROM:
"my fav artist - title album song.mp3"
TO:
"My Fav Artist - Title album song.mp3"
Use:
We split the file name at the dash and then modify the case different for the part before, and the part after the dash.

var  
  Delimiter, Extension, Part1, Part2, Part2Char1, Part2Rest: WideString;
  PosOfDelimiter: Integer;
begin
  Delimiter := '-';
  PosOfDelimiter := Pos(Delimiter, FileName);

  if (PosOfDelimiter > 0) then
    begin
       Extension  := WideExtractFileExt(FileName)
       Part1      := WideCopy(WideExtractBaseName(FileName),                 1, PosOfDelimiter -2 );
       Part2      := WideCopy(WideExtractBaseName(FileName), PosOfDelimiter +2, Length(FileName)  );
       Part2Char1 := WideCopy(Part2, 1,      1           );
       Part2Rest  := WideCopy(Part2, 2, Length(Part2) -1 );

       //ShowMessage('Debug: #' + Part1 + '#' + Part2 + '#'  + Part2Char1 + '#' + Part2Rest + '#');

       FileName := WideCaseCapitalize(Part1)
                  + ' ' + Delimiter + ' '
                  + WideUpperCase(Part2Char1) + WideLowerCase(Part2Rest)
                  + WideUpperCase(Extension);
    end;
end.

To split an file name with regular expression you can use something like this:
Note that you have to adjust the RegEx by your needs, according to your real file names.

var
  Parts: TWideStringArray;
begin
  Parts := SubMatchesRegEx(WideExtractBaseName(FileName), '(.)(.+_)(.+_)(.+)', FALSE);
  If (Length(Parts) <=0) then exit;

 FileName := WideUpperCase(Parts[0]) + Parts[1] + WideUpperCase(Parts[2]) + Parts[3]  + WideExtractFileExt(FileName);
end.


Here we are using RegEx and WideCopy() to split an string into parts.

For an example file name like
"Dzenan Loncarevic - 2009 - 10 - Laura (Bonus).mp3"
our message will look like:
"Dzenan Loncarevic - 2009 - 10 - # Laura (Bonus).mp3"

var
  Parts: TWideStringArray;
  Base, Part1, Part2: WideString;  
begin
  Base := WideExtractBaseName(FileName);

  //Find last '-' by greedy RegEx:
  Parts := SubMatchesRegEx(Base, '(.+-)(.+)', FALSE);
  If (Length(Parts) <=0) then exit;

  //Split file name into two:
  Part1 := WideCopy( Base,       1            , Length(Parts[0]) );
  Part2 := WideCopy( Base, Length(Parts[0]) +1,         999      );

  WideShowMessage(Part1 + ' # ' + Part2  + WideExtractFileExt(FileName));
end.

How did this works?
See yourself:
Add to the code, right under

 If (Length(Parts) <=0) then exit;

this two commands:

ShowMessage( Parts[0] );
ShowMessage(  IntToStr(  Length(Parts[0]) ) );

Or with more infos:

ShowMessage( '=' + Parts[0] + '='      + #13#10 + '=' + Parts[1] + '=' );
ShowMessage( IntToStr(Length(Parts[0]))  +#13#10+   IntToStr(Length(Parts[1])) );

Hints:
Putting the '=' -signs (or similar) around the content will let you spot additional spaces more easier.
Since "Length(Parts[n])" will provide an number/digit, and ShowMessage() only allows chars, we have to convert 'Int-to-Chars'.
Then you will see that
Parts[0] will hold "Dzenan Loncarevic - 2009 - 10 -" and
the length of this string in 'Parts[0]' is '31'.
So we can use this info as parameter for WideCopy().

Ahh, yes: the '999' for 'Part2' just means: "give me all till the end", since an average file name is 25 chars only. Maybe '100', but not '999', isn't it?
And with this little trick ReNamer gives me all chars till the end, no matter how many that are.


We can also use Split() to split an file name into parts:

// Swaps FileName-parts at minus-sign.pas
// FROM: "Artist - Song.mp3"
// TO: "Song - Artist.mp3"
var
  Parts: TWideStringArray;
  SplitSign: String;  
  Count: integer;

begin

  // sign to split the file name, e.g. for "Artist - Song.mp3" we split at ' - '
     SplitSign = ' - ';

  //Trick to ask the user for an delimiter. Using 'count' var to prompt only once.
     //If count < 1 Then
        //SplitSign := InputBox('Split FileName', 'Insert the sign where you want to split the FileName into parts:', SplitSign);
       //Count := 2

  // split the filename at '-' into parts:
     Parts := WideSplitString(WideExtractBaseName(FileName), SplitSign);
     // Note: parts are numbered in array from 0 on: 0, 1, 2, 3... So first part has the index '0'

  // build your new name:
     // Here: second part[1]  first, then SpaceMinusSpace, then the first part[0]:
     FileName := Parts[1] + ' - ' + Parts[0] + WideExtractFileExt(FileName);
end.

Please note: to split file name you can use also the Arrange Rule (see ReNamer beta and the wiki about rules)