Shell Scripting: extracting path from filename
Howdy, folks! I'm wrestling with a bash script and I'm stuck.
Are there any gurus in the house who can suggest a way to move to a directory where a particular file resides? For example, an argument to my script may be 'somedir/moredir/file.txt'. How can I cd to the directory that the file is in? Is there any way to extract the path to the that text file into a variable?
Any tips would be appreciated...
April 06, 2005 10:45 PM
use basename or dirname to extract the path / filename
[root@moonshine ~]# basename 'somedir/moredir/file.txt'
file.txt
[root@moonshine ~]# dirname 'somedir/moredir/file.txt'
somedir/moredir
so $dir = `dirname 'somedir/moredir/file.txt'`
hope that helps,
Chris
[root@moonshine ~]# basename 'somedir/moredir/file.txt'
file.txt
[root@moonshine ~]# dirname 'somedir/moredir/file.txt'
somedir/moredir
so $dir = `dirname 'somedir/moredir/file.txt'`
hope that helps,
Chris
Holy @^#&! Talk about fast response... this solves my problem. Thank you very much, Chris. Will this work on other shells besides BASH as well?
It should since (at least on my system) dirname and basename are binary programs in /bin, not builtin commands of bash.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement