1846541 Members
2037 Online
110256 Solutions
New Discussion

Script commands

 
SOLVED
Go to solution
bhoang
Advisor

Script commands

I need some help to identify the filename and the associated pathname that the users
input when executing a script.
Suppose the users input two following files:
/path1/path2/path3/file1 and
/path1/path2/file2
Now, what command can I use to retrieve just
the file name and the pathname itself?
/path1/path2/path3 and file1
/path1/path2 and file2
TIA.
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor
Solution

Re: Script commands

Hi:

Use 'basename' to get the filename. Use 'dirname' to get the directory name. See man pages for 'basename'.

For example:

dirname /usr/src/cmd/cat.c

returns /usr/src/cmd

...JRF...
This

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: Script commands

Hi:

Use 'basename' to get the filename. Use 'dirname' to get the directory name. See man pages for 'basename'.

For example:

dirname /usr/src/cmd/cat.c

returns: /usr/src/cmd

basename /usr/src/cmd/cat.c

returns: cat.c

...JRF...
Vladislav Demidov
Honored Contributor

Re: Script commands

You can use the next command s in your script
basename $0
dirname $0

refer to man page of basename command for additional information
John Palmer
Honored Contributor

Re: Script commands

Hi,

Are you trying to split a filename into the directory part and the file part?

If so then you can do it as follows:-

#/usr/bin/sh

FN=/path1/path2/path3/file
FILE=${FN##*/}
DIR=${FN%/*}

The FILE= construct removes all characters up to the final / leaving 'file'

The DIR= construct removes the final / and everything after it, leaving '/path1/path2/path3'

Hope this helps,
John
Kofi ARTHIABAH
Honored Contributor

Re: Script commands

Bach:

You can try:

FULL_PATH=/path1/path2/file

echo $FULL_PATH | awk -F/ '{ printf "filename is" $(NF) "nPath is: " } { for (i = 2 ; i < NF; i++) printf $(i) }'

make changes as required
nothing wrong with me that a few lines of code cannot fix!