【问题标题】:Normalize arbitrary file paths in bash on OSX在 OSX 上的 bash 中规范化任意文件路径
【发布时间】:2015-08-06 11:10:33
【问题描述】:

我正在寻找一种方法来规范化 bash 中的任意文件路径,将 ... 解析为它们的绝对值。例子:

> cd /foo/bar
> normalize_path "."   
/foo/bar
> normalize_path "../baz"
/foo/baz
> normalize_path "../../folder/that/doesnt/exist/"
/folder/that/doesnt/exist

请注意在上面的示例中,normalize_path 如何返回一个值即使路径不对应于真实的文件夹或文件。我在 StackOverflow(example 1example 2)上看到的关于绝对或规范化路径的所有先前问题都假定路径指向真实文件并使用 realpathpwd 对其进行规范化,但这不起作用对于我的用例。

换句话说,我正在寻找一个 bash 函数,它纯粹将路径作为字符串进行操作,实际上并不查看文件系统,类似于 Java 中的 File.getCanonicalPath

【问题讨论】:

  • 必须单独在bash 中还是可以使用readlink -m your_imaginary_path_hererealpath -m your_imaginary_path_here
  • @rickhg12hs:我正在寻找可以在 OS X 上运行的东西。

标签: macos bash file path


【解决方案1】:

Readlink 是要走的路,或者在你的情况下是 greadlink。它在 GNU 核心实用程序包中。 “brew install coreutils”(如果您使用自制软件)。然后像 rickhg12hs 说的那样使用 greadlink -m ../my_silly_filename.txt。

【讨论】:

  • 啊,我不知道greadlink 有一个-m 参数!我已经尝试过-f,正如许多其他答案中所建议的那样,如果文件不存在,它就不起作用。但是-m,又名--canonicalize-missing 正是我想要的。谢谢!
猜你喜欢
  • 2010-09-22
  • 1970-01-01
  • 2010-11-17
  • 2016-01-09
  • 2016-11-10
  • 1970-01-01
  • 1970-01-01
  • 2014-04-16
  • 2010-10-15
相关资源
最近更新 更多