Find the answer to your Linux question:
Results 1 to 5 of 5
Hi I want to extract the name of a file from its absolute path. so for e.g. I have a variable: file=/logs/temp/t.out so from the variable file i just want ...
  1. #1
    Just Joined!
    Join Date
    Jun 2007
    Location
    UK
    Posts
    14

    extracting file-name from absolute path

    Hi

    I want to extract the name of a file from its absolute path.

    so for e.g.
    I have a variable:
    file=/logs/temp/t.out

    so from the variable file i just want to extract: t.out

    Whats the best possible way for this?

    or simply put does the cut command allow to cut the last occurance of a delimeter?

    cheers
    ali

  2. #2
    Linux Engineer khafa's Avatar
    Join Date
    Apr 2008
    Location
    Tokyo, Japan
    Posts
    858
    hi,



    basename is for that
    example
    Code:
    [me@home]$ var=/bin/ls
    [me@home]$ basename $var
    [me@home]$ ls
    Linux and me it's a love story

  3. #3
    Just Joined!
    Join Date
    Jun 2007
    Location
    UK
    Posts
    14
    cheers khafa

    also found:
    fName=`echo $file | awk -F/ '{ print $(NF) }' `

    I am not sure which one is more efficient though

  4. #4
    Linux Engineer khafa's Avatar
    Join Date
    Apr 2008
    Location
    Tokyo, Japan
    Posts
    858
    Quote Originally Posted by alinaqvi90 View Post

    also found:
    fName=`echo $file | awk -F/ '{ print $(NF) }' `

    I am not sure which one is more efficient though
    basename should be more efficient as it is built for this purpose
    Linux and me it's a love story

  5. #5
    Linux Guru
    Join Date
    Nov 2007
    Location
    Córdoba (Spain)
    Posts
    1,513
    basename is probably the best all-rounds tool for this, more efficient and easier to use without a doubt.

    However, if you don't need portability (i.e. you are sure you will always use bash), you can use a bash builtin for string mangling for an slight efficiency gain (since it's a builting, no new process needs to be created).

    Code:
    $ file="/home/i92guboj/my random file.txt"
    $ echo ${file##*\/}
    my random file.txt
    As said, this is shell specific stuff, so forget about it unless you are sure you'll be using bash and in that case, don't forget to add the correct shabang on the first line of your script.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...