3

I have requirement to extract the filename from a given path for e.g. /dev/user/test.csv. I need location /dev/user/ in separate variable and file name test.csv in different variable.
Could someone please suggest a solution ?

don_crissti
  • 79,330
  • 30
  • 216
  • 245
chhaya vishwakarma
  • 693
  • 6
  • 12
  • 18

1 Answers1

6

Normally

basename "/dev/user/test.csv" # produce «test.csv»
dirname "/dev/user/test.csv"  # produce «/dev/user»

In some shell's (like bash e.g.) you can use variable expansion

var="/dev/user/test.csv"
echo ${var##*/}               # produce «test.csv»
echo ${var%/*}                # produce «/dev/user»

If /dev/user/test.csv exist you can divide what you want by simple trick:

find /dev/user/test.csv -printf '%h\t%f\n'
Costas
  • 14,806
  • 20
  • 36
  • Thanks that works for me but there is one problem I'm looping through set of folders if path is like "/dev/user" (without filename) I get "/dev" in path variable and "user" in file variable how can i avoid this ? – chhaya vishwakarma Oct 29 '15 at 13:14
  • Much better if you show full code because to parce the output of `ls` command can lead to mistakes – Costas Oct 29 '15 at 17:27
  • Hi Thanks I'm facing another problem I appreciate if you can suggest something.....since Im looping through list of directories some directory names are like "dev user" , this list I store in array and try to get "basename" and "dirname" since there is space coming in between I'm not getting "basename" and "dirname" correctly its breaks up on space – chhaya vishwakarma Nov 05 '15 at 10:57
  • @chhayavishwakarma U should provide correct looping. While I did not see you code I cannot advise you – Costas Nov 05 '15 at 11:35