2

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

1
  • I don't get what you are asking myself.. but could just be me :-) Sep 15, 2009 at 14:44

4 Answers 4

1

Actually, it is realpath: http://linux.about.com/library/cmd/blcmdl3_realpath.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
1
  • 2
    or just (cd /foo/../bar && pwd) Sep 16, 2009 at 11:09
9

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'.

2
  • 1
    -f: all but the last component must exist, -e: all components must exist, -m: no requirement for existence Sep 15, 2009 at 16:26
  • readlink is not guaranteed to be on a given system, that might be an issue Sep 15, 2009 at 22:52
1

Are ou asking for the basename command ?

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

And there is also the other part : dirname

$ dirname ../../.bashrc
../..
1
  • 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. Sep 16, 2009 at 11:07
1

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")'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .