gpt4 book ai didi

regex - 有没有在 bash 中用代字号替换主目录的好方法?

转载 作者:行者123 更新时间:2023-11-29 08:44:04 24 4
gpt4 key购买 nike

我正在尝试使用路径并在 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);
}

最佳答案

我不知道有什么方法可以直接将其作为变量替换的一部分来执行,但您可以将其作为命令执行:

[[ "$name" =~ ^"$HOME"(/|$) ]] && name="~${name#$HOME}"

请注意,这并不完全符合您的要求:它将“/home/alice/”替换为“~/”而不是“~”。这是有意为之的,因为有些地方的尾部斜杠很重要(例如 cp -R ~/backups 做的事情与 cp -R ~//backups 不同)。

关于regex - 有没有在 bash 中用代字号替换主目录的好方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10036255/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com