System Administration

Re: Parse between the path and the filename.

 
SOLVED
Go to solution
Adam Prince
Occasional Contributor

Parse between the path and the filename.

I am writing a script where I need to have the user
enter in the destination file such as /tmp/ps_data or
/usr/local/sbin/temp.txt. I need to be able to parse the dest_path and dest_filename into two varibles. I have know idea how to do this so any help would be much appreciated. Thanks Adam
7 REPLIES 7
Jeff Machols
Esteemed Contributor

Re: Parse between the path and the filename.

Try something like this to get the name of the file

NAME=`echo $INPUT| awk -F/ '{print $NF}'
path
James R. Ferguson
Acclaimed Contributor

Re: Parse between the path and the filename.

Hi Adam:

You can use 'basename' and 'dirname' to obtain the filename and the directory name, respectively. See 'man basename'.

Regards!

...JRF...
Marco Paganini
Respected Contributor
Solution

Re: Parse between the path and the filename.

Hello Adam,

Try this:

Let's suppose:

fullname=/usr/src/cow/sheep.c

To separate:


filename=`basename $fullname`

pathname=`echo $fullname | sed -e "s/$filename$//g"`

Hope it helps,
Paga
Keeping alive, until I die.
Joseph C. Denman
Honored Contributor

Re: Parse between the path and the filename.

Hi adam,

I would do as James has stated. use "basename" and "dirname".

example:

echo "please enter path/filename: \c"
read answer

filename=`basename $answer`
dirname=`dirname $answer`

hope this helps

...jcd...
If I had only read the instructions first??
Rodney Hills
Honored Contributor

Re: Parse between the path and the filename.

With shell substitution-

x="/abc/def/ghi"
$ echo ${x##*/}
ghi
$ echo ${x%/*}
/abc/def

## matches pattern left to right
%% matches pattern right to left

-- Rod Hills
There be dragons...
Praveen Bezawada
Respected Contributor

Re: Parse between the path and the filename.

hi
you can use 'basename' and 'dirname'

if you want something cool
try
for eachfile in `ls`
fname=${eachfile##[./]}
echo $fname
done

...BPK...
Adam Prince
Occasional Contributor

Re: Parse between the path and the filename.

Wow, thanks for all the input!
It is much appreciated.
Adam