Is there a command line tool in linux that will 'normalize' a filename? i.e. remove all "xx/./xx" parts, or "myfolder/../myotherfolder" parts?

link|improve this question

79% accept rate
I don't get what you are asking myself.. but could just be me :-) – Kyle Brandt Sep 15 '09 at 14:44
feedback

4 Answers

up vote 1 down vote accepted

Actually, it is realpath: http://linux.about.com/library/cmd/blcmdl3%5Frealpath.htm

There is also a command-line version: cyberciti.biz/faq/unix-linux-bsd-find-real-physical-path/

But on my CentOS 5 it is not available by default.

Also there is a "cheating way":

$ bash -c "cd /foo/../bar/ ; pwd"
/bar
link|improve this answer
1  
or just (cd /foo/../bar && pwd) – reinierpost Sep 16 '09 at 11:09
feedback

readlink -f seems to do it (despite being intended for de-referencing symlinks):

[root@noldevvg19 ~]# readlink -f /etc/../usr/../etc/./sysconfig/../redhat-release 
/etc/redhat-release

I believe this is called 'canonicalizing'.

link|improve this answer
1  
-f: all but the last component must exist, -e: all components must exist, -m: no requirement for existence – Dennis Williamson Sep 15 '09 at 16:26
readlink is not guaranteed to be on a given system, that might be an issue – Thorbjørn Ravn Andersen Sep 15 '09 at 22:52
feedback

Are ou asking for the basename command ?

$ basename ../../.bashrc
.bashrc

And there is also the other part : dirname

$ dirname ../../.bashrc
../..
link|improve this answer
They are related, but they are not the answer. One reason they aren't is that they just take one step; another is that they just rewrite the strings without looking at the file system, which may go wrong in the presence of symlinks. – reinierpost Sep 16 '09 at 11:07
feedback

With python line command:


python -c 'import os; print os.path.basename("/home/mezgani/nat")'
python -c 'import os; print os.path.direname("/home/mezgani/nat")'

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.