我正在尝试使用路径,并用bash中的波浪号替换主目录,我希望用尽可能少的外部程序来完成这项工作。有没有办法只用bash就能做到。我得到了
${PWD/#$HOME/\~}但这并不完全正确。它需要转换为:
/home/alice to ~
/home/alice/ to ~/
/home/alice/herp to ~/herp
/home/alicederp to /home/alicederp值得注意的是,下面是bash源如何在转换\w value in the prompt时执行此操作。
/* Return a pretty pathname. If the first part of the pathname is
the same as $HOME, then replace that with `~'. */
char *
polite_directory_format (name)
char *name;
{
char *home;
int l;
home = get_string_value ("HOME");
l = home ? strlen (home) : 0;
if (l > 1 && strncmp (home, name, l) == 0 && (!name[l] || name[l] == '/'))
{
strncpy (tdir + 1, name + l, sizeof(tdir) - 2);
tdir[0] = '~';
tdir[sizeof(tdir) - 1] = '\0';
return (tdir);
}
else
return (name);
}发布于 2012-04-06 07:07:44
我不知道有什么方法可以直接作为变量替换的一部分来完成,但是你可以通过命令来完成:
[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}"请注意,这并不完全符合您的要求:它将"/home/alice/“替换为"~/”而不是"~“。这是故意的,因为有些地方尾部的斜杠很重要(例如,cp -R ~ /backups做了一些与cp -R ~/ /backups不同的事情)。
https://stackoverflow.com/questions/10036255
复制相似问题