Description
Given a file path like /a/e/../b/f/../c/./d/, which is not canonical, since the equivalent shortest path is /a/b/c/d/.

To get the canonical form of a path, perform the following actions:
  • Action-1: replace /./ with /,
  • Action-2: replace the beginning /.. with /, and
  • Action-3: replace /some_dir/../ with /.
Raw Input Desired Output
/a/b/c/d/
/a/e/../b/f/../c/./d/
/a/e/g/../../b/h/i/../../c/d/
/.././a/./b/e/.././c/d/./
/a/b/c/d/
/a/b/c/d/
/a/b/c/d/
/a/b/c/d/
Script and Comments
Script1
[ 1] :0
[ 2] s|/\./|/|
[ 3] t 0
[ 4] s|^(/\.\.)+/|/|
[ 5] :1
[ 6] s|/[^/]+/\.\./|/|
[ 7] t 1
Comments
  1. To make sed interpret REs as EREs, the `-r' option of GNU sed must be used.
  2. The default delimiter of command `s' is `/' such that we have to escape every literal slash. But this will make the command difficult to read. In this script, we choose `|' as the delimiter instead of the default `/'.
  3. Steps [1] thru [3] perform Action-1.
  4. Step [4] performs Action-2.
  5. Steps [5] thru [7] perform Action-3.