Extract a filename from a file path

Introduction

This article demonstrates how to extract a filename from a file path. The example function will extract the filename and extension when it is supplied a complete Windows file path (as a string parameter).

This is useful when doing file manipulation or FTP processing — or any time when you only need the filename and not the whole path.

Note: The example function supplied only works on Windows systems, because it recognizes Windows file path structure and separators (like “\”). Whereas other systems like Linux/Unix/Mac use different file path structure and separators (like “/”).

It should be quite simple to adapt the code for other systems, if you need help to do this please contact us at support@interfaceware.com.

Task [top]

Use the supplied function to extract the filename from a file path (supplied as a string parameter to the function).

Implementation [top]

Simply use this function in your code:

--This function finds the filename when given a complete path 
function GetFilename(path)   
    local start, finish = path:find('[%w%s!-={-|]+[_%.].+')   
    return path:sub(start,#path) 
end

Follow these steps:

  1. We recommend adding it in a local module or a shared module something like “file.utils”:
    local module extract filename

    local file_utils = {}
    
    --This function finds the filename when given a complete path
    function file_utils:GetFilename(path)
       local start, finish = path:find('[%w%s!-={-|]+[_%.].+')
       return path:sub(start,#path)
    end
    
    return file_utils
    
  2. Then you can call it like this from another module:
    Note: This is shown in the main module — but it works the same way in any module.
    calling get filename

    local utils = require 'file.utils'function 
    
    myFunction()
       local filepath = 'C:\\Program Files\\iNTERFACEWARE\\Iguana\\License.txt' -- separators escaped
       local filename = utils.GetFilename(filepath)
       trace(filename)
    
       path = [[C:\Program Files\iNTERFACEWARE\Iguana\License.txt]]             -- separators not escaped
       filename = utils.GetFilename(path)
       trace(filename)
    end

How it works [top]

This function uses Lua string manipulation to strip the filename from a given path. This function will work regardless of if the filename has space characters in it.

For example, if supplied the file path as a string:

‘C:\\Program Files\\iNTERFACEWARE\\Iguana\\License.txt’
[[C:\Program Files\iNTERFACEWARE\Iguana\License.txt]]

It will return the string:

‘License.txt’

This will match any letter or digit <%wOR any whitespace character <%sOR any punctuation character in the range of ! to = and { to | <!-={-|> (This excludes the \ character ) as well as any characters leading up to the file extension.

More information [top]

 

 

Leave A Comment?