Pull Filename from Path

We have a 2012 database with an imported table and want to pull just the file name from a full path.  For example if the path is G:\Everyone\Import\CIIUS.XLS then I want to pull just the CIIUS.XLS out.  I have tried the following code but
it is not working correctly.  Thanks.
SELECT RIGHT(RTRIM([filepath]),CHARINDEX('\',REVERSE([filepath]))-1)

I noticed you've used an RTRIM on the string side of RIGHT. This might be where your problem lies. You are trimming the string, but not the CHARDINDEX. If filepath ends in a whitespace you'll end up with a string that starts with a \.
You can either trim both sides, or trim the whole:
DECLARE @table TABLE (filepath VARCHAR(200))
INSERT INTO @table (filepath) VALUES ('G:\Everyone\Import\CIIUS.XLS '),('G:\CIIUS.XLS')
SELECT RIGHT(RTRIM(filepath),CHARINDEX('\',REVERSE(RTRIM([filepath])))-1)
FROM @table
SELECT RTRIM(RIGHT(filepath,CHARINDEX('\',REVERSE([filepath]))-1))
FROM @table
Don't forget to mark helpful posts, and answers. It helps others to find relevant posts to the same question.

Similar Messages

  • Regexp problem when extracting filename from path

    I'm trying to extract filename and full path from string: \dir1\dir2\file.name
    import java.util.regex.*;
    public class Main {  
        private static final String REGEX = "(\\S*\\)*(\\S*)";
        private static final String INPUT = "\\dir1\\dir2\\file.name";
        public Main() {    }   
        public static void main(String[] args) {
           Pattern p = Pattern.compile(REGEX);
           Matcher m = p.matcher(INPUT); // get a matcher object
           int count = 0;      
           if(m.find()) {
               count++;          
               System.out.println("group1: "+m.group(1));
               System.out.println("group2: "+m.group(2));                     
    }I expect group1 to be \dir1\dir2\ and group2 file.name
    when I run program exception is thrown:
    Exception in thread "main" java.util.regex.PatternSyntaxException: Unclosed group near index 12
    (\S*\)*(\S*)
    ^
    at java.util.regex.Pattern.error(Pattern.java:1650)
    at java.util.regex.Pattern.accept(Pattern.java:1508)
    at java.util.regex.Pattern.group0(Pattern.java:2460)
    at java.util.regex.Pattern.sequence(Pattern.java:1715)
    at java.util.regex.Pattern.expr(Pattern.java:1687)
    at java.util.regex.Pattern.compile(Pattern.java:1397)
    at java.util.regex.Pattern.<init>(Pattern.java:1124)
    at java.util.regex.Pattern.compile(Pattern.java:817)
    at javaapplication2.Main.main(Main.java:15)

    'jverd' is right but if you are just trying to split the INPUT into a path + filename then why not just look for the last '\'. i.e.
    int lastSlash = INPUT.lastIndexOf('\\');
    String group1 = INPUT.substring(0, lastSlash);
    String group2 = INPUT.substring(lastSlash+1);
    As it stands, your example will not give you group 1 as \dir1\dir2. For that you would need something like
    "((?:\\[^\\])*)(\\.*)"
    to make sure you capure all the path in group 1.

  • Use regular expressions to extract .llb filename from path

    I am trying to be clever (always a dangerous thing) and use a regular expression to extract the name of a library from a filepath converted to a string.   Whilst I appreciate there are other ways to do this, regex would appear to be a very powerful neat way, should I be able to get it to work.
    i.e if I have a string of the type, C:\applications\versions\library.llb\toplevel.vi, I want to be able to extract library.llb from the string, given that it will be of variable length, may include numbers & spaces and may be within a file hierarchy of variable depth.   In other words, I want to extract the portion of the string between the last \ that ends with .llb
    The best I have managed so far, is \\+.*llb which returned everything minus the drive letter and the toplevel.vi
    Can anyone help me achieve this, or am i better using an alternative method (e.g filepath to array string, search for .llb)
    Thanks
    Matt
    Solved!
    Go to Solution.

    Hi Matt,
    attached you'll find two other options.
    Mike
    Message Edited by MikeS81 on 04-13-2010 01:30 PM
    Attachments:
    Path.PNG ‏7 KB

  • Filename from complete file path

    Hi,
       can anybody let me know the method to get the filename from the complete filepath( this path includes both directory as well as filename)
    regards.
    venkat.

    Hi,
    Check the below code:
    data : ig_path type standard table of tp_path,
           wg_path type tp_path.
    data : g_lines     type i          ,
           g_filename  type string     .
    parameter : p_input type rlgrap-filename.
      split p_input at '\' into table ig_path.
      describe table ig_path lines g_lines.
      read table ig_path index g_lines into wg_path.
      g_filename = wg_path-val.
    write : g_filename.
    Regards,
    Raghu

  • How to get FILENAME from FILE PATH

    does anyone know how to get filename from a file path for example
    FILE PATH: C:\Project\uploadbean\web\uploads\Button.txt
    returns
    FILENAME: Button.txt

    @BalusC
    ust for a reference cause i'm new in JSP This has nothing to do with JSP, but with basic knowledge of an essential API. I have given you the link to the File API. Are you saying that you refused to read the API documentation, which clearly explains you how to use the File and shows which methods are all available to you undereach the straightforward getName() method, and expecting that the others may chew the answers for you? Loser.

  • Extract filename from a path

    Hi folks!
    Anybody knows if there is a MF to extract the filename from a path...
    for example, if i have a path like:
    server\filename.ext
    c:filename.ext
    c:\>filename.txt
    i want to extract the filename: 'filename.ext' (or just, 'filename')
    Thank's in advance!
    Xavi.

    Hi,
    You can use the FM <b>CACS_SPLIT_PATH</b>
      Import parameters               Value         
      I_PATH                          C:TEST.TXT                                                                               
    Export parameters               Value         
      E_PATH                          C:           
      E_FILENAME                      TEST.TXT      
      E_PSERVER                       X  
    Regards
    vijay

  • Method to obtain filename apart from path

    I have a string
    String myString = C:\foo\bar\myFile.txt;I wish to obtain only the value myFile.txt, that is the name of the File.
    I use the File object
    File fileObj = new File( myString );
    String fileName = fileObj.getName();Running this in one environment yeilds the desired "myFile.txt". But in another environment it yeilds "C:\foo\bar\myFile.txt".
    How can this be?
    Thanks for any help

    I'm going to assume what may be obvious and that is that the method works only within the current operating system. In another words, it's not a "all knowing" method that can parse a filename from a string using the separator characters of each operatiing system "\" and "/". So it's not an effective means to accomplish what I need when the information is going from one OS, to another...
    Yes - It's in the API docs which I'm reading now. I don't know why I made this mistake, unless I was confused by the following..."This class presents an abstract, system-independent view of hierarchial pathnames". But immediately following it says that the prefix strings to the filename are system-dependent.
    Edited by: nantucket on May 16, 2008 1:32 PM
    Edited by: nantucket on May 16, 2008 1:36 PM

  • Screensaver pulling images from who knows where...

    All,
    I'm a bit confused here. My screen saver used to be an album in my iPhoto. However, seemingly out of nowhere, it was pulling images from who knows where and all over the place.
    I have deleted my iPhoto library and re-imported my images and re-made my albums. But, have not fixed the problem. I have also verified and repaired permissions and rebooted also not fixing the problem.
    Any help would be greatly appreciated.

    Try com.apple.screensaver.[long alphanumeric number].plist, if you can find it on your machine. I just changed my Screensaver preferred folder and then did a File Buddy search for .plist files that had been modified in the last 5 minutes, and that one turned up — among a few others. I doubt that the number in your plist's filename would or should be the same as mine, and that's why I didn't include mine above. The path to my file is:
    HD>Users>My username>Library>Preferences>ByHost>file

  • Trying to add filename and path in footer of Word doc and it only lets me "Convert to PDF"?

    I am running MS Office 03 and just installed Acrobat 9.0 Pro. When I try to insert the Filename and Path from the insert option of the footer properties, it only gives me the option to "Convert to PDF". I don't know why it's doing this, but it started after the install of Acrobat 9.0. What should I do?

      To get the path ... event.target.path;
    To get the file name .... event.target.documentFileName;

  • Filename and path sizes and characters

    I am failing to load 4000+ tracks to my Ipod from my XP machine using Itunes 7.50.0.20. This is an Ipod Clickwheel 20GB. I want to load 17.86GB in the now empty Ipod. However it gets so far then stops saying there is not enough space.
    I wonder if am I getting the wrong message?
    Some of my tracks have very long filenames/paths e.g 124 charactere filenames and 213 character paths. I also have some filenames with " (double quote) in.
    Could this be the reason?
    If so what characters must I avoid and what size should the filename and paths be limited to?

    Filenames and paths are irrelevant. They are renamed on the iPod anyway.
    20 GB is not really 20. It is a rounded number all HD manufacturers use. Plus you lose some space due to formatting and the iPod software. There is also meta data for the songs which takes some space.

  • Unable to connect to the server to pull data from mysql

    Hello,
    I am novice working with Flash Builder 4 and I just created a test application which runs well in my computer pulling data from Mysql using PHP and populating a datagrid. But when I transfered it to the my hosting provider failed. I have been doing some modifications to the gateway.php and amf.config.ini to solve some of the issues. Now the application try to run but doesn't populate the data in the datagrid. I included a tracking point in my data service file to read the connections variables, but they come up in blank. I highly appreciate any help. Here are my gateway.php, amf.config.ini and the data service.
    gateway.php
    <?php
    ini_set("display_errors", 1);
    $dir = dirname(__FILE__);
    $webroot = $_SERVER['DOCUMENT_ROOT'];
    $configfile = "$dir/amf_config.ini";
    $fp = fopen("tracking.txt", "a");
    fwrite($fp, "1-config file " . $configfile . "\r\n");
    //default zend install directory
    $zenddir = $webroot. '/ZendFramework/library';
    //-$zenddir = $webroot;
    fwrite($fp, "2-default zendir" . $zenddir . "\r\n");
    //Load ini file and locate zend directory
    if(file_exists($configfile)) {
         $arr=parse_ini_file($configfile,true);
         if(isset($arr['zend']['webroot'])){
              $webroot = $arr['zend']['webroot'];
              $zenddir = $webroot. '/ZendFramework/library';
         if(isset($arr['zend']['zend_path'])){
              $zenddir = $arr['zend']['zend_path'];
    fwrite($fp, "3-after zendir" . $zenddir . "\r\n");
    // Setup include path
    //add zend directory to include path
    set_include_path(get_include_path().PATH_SEPARATOR.$zenddir);
    // Initialize Zend Framework loader
    require_once 'Zend/Loader/Autoloader.php';
    //-require_once 'Autoloader.php';
    Zend_Loader_Autoloader::getInstance();
    // Load configuration
    $default_config = new Zend_Config(array("production" => false), true);
    $default_config->merge(new Zend_Config_Ini($configfile, 'zendamf'));
    $default_config->setReadOnly();
    $amf = $default_config->amf;
    fwrite($fp, "4- configfile" . $dafault_config["production"] . "\r\n");
    // Store configuration in the registry
    Zend_Registry::set("amf-config", $amf);
    // Initialize AMF Server
    $server = new Zend_Amf_Server();
    $server->setProduction($amf->production);
    if(isset($amf->directories)) {
         $dirs = $amf->directories->toArray();
         foreach($dirs as $dir) {
             // get the first character of the path.
             // If it does not start with slash then it implies that the path is relative to webroot. Else it will be treated as absolute path
             $length = strlen($dir);
             $firstChar = $dir;
             if($length >= 1)
                  $firstChar = $dir[0];
             if($firstChar != "/"){
                  // if the directory is ./ path then we add the webroot only.
                  if($dir == "./"){                  
                       $server->addDirectory($webroot);
                  }else{
                       $tempPath = $webroot . "/" . $dir;
                        $server->addDirectory($tempPath);
              }else{
                      $server->addDirectory($dir);             
    fwrite($fp, "5-temp path" . $tempPath . "=>" . "\r\n");
    fwrite($fp, "******************************************" . "\r\n");
    // Initialize introspector for non-production
    if(!$amf->production) {
         $server->setClass('Zend_Amf_Adobe_Introspector', '', array("config" => $default_config, "server" => $server));
            $server->setClass('Zend_Amf_Adobe_DbInspector', '', array("config" => $default_config, "server" => $server));
    // Handle request
    echo $server->handle();
    ?>
    amf.config.ini
    [zend]
    ;set the absolute location path of webroot directory, example:
    ;Windows: C:\apache\www
    ;MAC/UNIX: /user/apache/www
    ;-webroot =c:/wamp/www/
    webroot = /home/frutiexp/public_html
    ;set the absolute location path of zend installation directory, example:
    ;Windows: C:\apache\PHPFrameworks\ZendFramework
    ;MAC/UNIX: /user/apache/PHPFrameworks/ZendFramework
    ;zend_path = /home/frutiexp/public_html/ZendFramework
    [zendamf]
    amf.production = true
    amf.directories[]=fb41/services
    ;amf.directories[]=./
    CoursesService.php
    <?php
    *  README for sample service
    *  This generated sample service contains functions that illustrate typical service operations.
    *  Use these functions as a starting point for creating your own service implementation. Modify the
    *  function signatures, references to the database, and implementation according to your needs.
    *  Delete the functions that you do not use.
    *  Save your changes and return to Flash Builder. In Flash Builder Data/Services View, refresh
    *  the service. Then drag service operations onto user interface components in Design View. For
    *  example, drag the getAllItems() operation onto a DataGrid.
    *  This code is for prototyping only.
    *  Authenticate the user prior to allowing them to call these methods. You can find more
    *  information at <link>
    class CoursesService {
         var $username = "myusername";
         var $password = "mypassword"
         var $server = "localhost";
         var $port = "3306";
         var $databasename = "frutiexp_trainsur";
         var $tablename = "courses";
         var $connection;
          * The constructor initializes the connection to database. Everytime a request is
          * received by Zend AMF, an instance of the service class is created and then the
          * requested method is invoked.
         public function __construct() {
                $this->connection = mysqli_connect(
                                              $this->server, 
                                              $this->username, 
                                              $this->password,
                                              $this->databasename,
                                              $this->port
    $fp = fopen("./tracking.txt", "a");
    fwrite($fp, "1-service".  $databasename . " " . $username . "\r\n");
    fclose($fp);
              $this->throwExceptionOnError($this->connection);
          * Returns all the rows from the table.
          * Add authroization or any logical checks for secure access to your data
          * @return array
         public function getAllCourses() {
              $stmt = mysqli_prepare($this->connection, "SELECT * FROM $this->tablename");         
              $this->throwExceptionOnError();
              mysqli_stmt_execute($stmt);
              $this->throwExceptionOnError();
              $rows = array();
              mysqli_stmt_bind_result($stmt, $row->cou_id, $row->cou_title, $row->cou_overview, $row->cou_objectives);
             while (mysqli_stmt_fetch($stmt)) {
               $rows[] = $row;
               $row = new stdClass();
               mysqli_stmt_bind_result($stmt, $row->cou_id, $row->cou_title, $row->cou_overview, $row->cou_objectives);
              mysqli_stmt_free_result($stmt);
             mysqli_close($this->connection);
             return $rows;
          * Returns the item corresponding to the value specified for the primary key.
          * Add authroization or any logical checks for secure access to your data
          * @return stdClass

    Hello Jdesko,
    Thank you for you prompt response. Yes, I have changed the connections variables in my dataservice ( I didn't post real values). You are right, after all I didn't make changes on the gateway.php except to add some tracking points. The one that I changed is the amf.config,ini. The application runs without any error exceptions, but don't populate the datagrid. According with the tracing is stoping just when establishing the connection to the database. Please let me know if you have any other clue. thanks

  • Getting filename from a string including filepath and filename

    How I can get a filename from a string which includes both
    filepath and filename? The filepath is not always the same. For
    example, the variable could include a "C:\temp\test.doc" or
    "C:\files\docfiles\test.doc" and I need to get the filename
    "test.doc" and save it to another variable. Thanks in
    advance.

    on getFilenameFromPath vPath
    oldDelim=the itemDelimiter
    the itemDelimiter=the last char of the moviePath
    iFilename=the last item of vPath
    the itemDelimiter=oldDelim
    return iFilename
    end
    Put that into a movie script. Then you can call the function
    any time
    to retrieve the last part of the path- like this:
    put getFilenameFromPath("C:\temp\test.doc")
    -- "test.doc"
    As an added bonus, it is cross-platform so it will work on a
    Mac as well
    as a PC.

  • Filename from field

    I have seen in past discussions about the difficluty and even impossibility of creating a SAVE AS filename from a field value in an Adobe form.  These discussions were posted back in 2006-2008.
    I am hoping that someone knows a relatively simple way to do this (if it's possible in Acrobat 10)  I am relatively new to Adobe and Javascripts.
    All I want to do is have a button that does a SAVE AS (I can do this), but pull the filename from the "NAME" field in the form and add the .pdf extension and place it in a particular directory on the server.
    Seems like this would be possible...  can anyone point me in the right direction?
    Thanks a million!!
    DMD    

    George,
    I think I should document exactly what is happening, so here goes…
    FROM ACROBAT X PRO - The form is working and saving via the mouse up JavaScript action coupled with the folder-level JS that contains;
    myTrustedSpecialTaskFunc   and  mySaveAs = app.trustPropagatorFunction
    In order to save it for READER users, I do a FILE, SAVE AS, READER EXTENDED PDF, ENABLE ADDITIONAL FEATURES.
    I copy the folder level JS over to the proper JS folder associated with READER
    I can open the file in READER and edit the form fields. 
    When I try to save the file using the Custom Save As button that works in ACROBAT, I get this error;
    NotAllowedError: Security settings prevent access to this property or method.
    Doc.saveAs:4:Field Save:Mouse Up
    NOTES:
    ·         I know that I am using the correct JavaScript folder for READER because I placed this JS code in the folder and it DOES display when I open READER-  app.alert("It works!");
    ·         I am saving the file in both instances to c:\temp\filename.pdf
    ·         When I distribute the form, I will be able to place the folder-level JS on the users machine.
    Per your last post, when I open the file that I have saved as above for READER in ACROBAT and go to file>properties>security I have the following displayed;
    Security: No Security
    Can be opened by: All versions of Acrobat
    Document Restrictions Summary
    Printing: Allowed
    Changing the document: Not allowed*
    Document assembly: Not allowed*
    Content copying: Allowed
    Content copying for accessibility: Allowed
    Page extraction: Allowed
    Commenting: Allowed
    Filling of form Fields: Allowed
    Signing: Allowed
    Creation of template pages: Not allowed*
    *This document restricts some Acrobat features in order to allow for extended features in Adobe Reader
    At this point, I am a a loss as to what is causing the error.  I hope this documentation helps you see where my problem is.
    Thanks,
    Dan

  • Oracle B2B 11g question about pulling data from remote TP sftp server

    Hi,
    We would like replace our custom b2b solution with oracle b2b, but without resulting much changes in remote TP side. To do that the following issues are to be resolved.
    1) in the existing custom b2b, host tp is pulling data from remote TP location. How does oracle b2b pull data from remote location using sftp(AS1 1.1)? Oracle document says that by using global listening channel, we can make oracle b2b listen to the sftp server? Is that correct? Is there any sample about how to configure and test it.
    2) For outbound file we would like to preserve the file name. If you use sftp for sending the file out, is it possible to preserve the filename?
    3) Some incoming files which are datafiles , does not have any identification pattern. Is there any other way to identify the document type? For example from which location we are pulling the file can tell us the document type.

    1) in the existing custom b2b, host tp is pulling data from remote TP location. How does oracle b2b pull data from remote location using sftp(AS1 1.1)? Oracle document says that by using global listening channel, we can make oracle b2b listen to the sftp server? Is that correct? Is there any sample about how to configure and test it. I am not sure what do you mean by AS1 1.1 but yes, SFTP is supported in Oracle B2B and if you want to poll a SFTP location, then you need to create a listening channel in Oracle B2B. For creating a listening channel, please refer -
    http://download.oracle.com/docs/cd/E14571_01/integration.1111/e10229/bb_listen_chan.htm#BAJJICJJ
    2) For outbound file we would like to preserve the file name. If you use sftp for sending the file out, is it possible to preserve the filename?Yes, it is possible. There is a setting "Preserve Filename" in transport protocol parameter of a SFTP channel which should be enabled for this purpose.
    3) Some incoming files which are datafiles , does not have any identification pattern. Is there any other way to identify the document type? For example from which location we are pulling the file can tell us the document type. In case of FTP/FILE/SFTP, file name can be used to pass document type and revision information to Oracle B2B. Please refer "Filename format" setting on the above mentioned link.
    I figured it out from another thread about how to pull the file. I configured the listening channel so that it reads from a remote server using sftpo protocol. And I have given the filename format as %FROM_PARTY%.dat. I am putting a file like TESTBC.dat. TESTBC is the name of the remote TP. B2B is reading the file but, recognizes the document tupe, but says that FromTP null. What is the solution?
    Make sure that TP name is same as what you are giving in filename (cross-check for spelling). You may also try with default naming convention (do not mention anything in Filename format in listening channel configuration) - %FROM_PARTY%_%TIMESTAMP%.dat
    for eg -
    Acme_12345.dat
    Regards,
    Anuj

  • For preparing the filenames and paths for the oracle database files..

    Hi,
    I am preparing the filenames and paths for the oracle database files.....but I am not able to complete this one...Will you Please help for filling this one.
    Controlfile ---- > select name from v$controlfile;
    Redologfile -- > select member from v$logfile;
    Datafile --------- > select tablespace_name,file_name from dba_data_files order by 1;
    Tempfile --------> select tablespace_name,file_name from dba_temp_files;
    Spfile -----------> show parameter spfile
    Pfile --------------->
    Passwordfile ---->
    tnsnames.ora -->
    listener.ora------>
    sqlnet.ora ------>
    oratab ------------->
    Thanks
    Shiju

    orashiju wrote:
    Hi,
    I am preparing the filenames and paths for the oracle database files.....but I am not able to complete this one...Will you Please help for filling this one.
    Controlfile ---- > select name from v$controlfile;
    Redologfile -- > select member from v$logfile;
    Datafile --------- > select tablespace_name,file_name from dba_data_files order by 1;
    Tempfile --------> select tablespace_name,file_name from dba_temp_files;
    Spfile -----------> show parameter spfile
    Pfile --------------->spfile and pfile are located under $ORACLE_HOME/dbs/
    Passwordfile ----> passwordfile is located under $ORACLE_HOME/dbs
    tnsnames.ora -->
    listener.ora------>
    sqlnet.ora ------>all above files are under $ORACLE_HOME/network/admin
    oratab ------------->depends on operating system. Usualy under /etc/oratab

Maybe you are looking for