如何从 tcsh 中的路径中删除文件名?

发布于 2024-07-26 08:13:08 字数 136 浏览 12 评论 0原文

给定 tcsh 中的这个变量:

set i = ~/foo/bar.c

如何获取 $i 的目录部分?

~/foo

Given this variable in tcsh:

set i = ~/foo/bar.c

how can I get just the directory part of $i?

~/foo

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

南渊 2024-08-02 08:13:09

这里有一些与上面不同的东西:
tcsh 中可用,但据我所知,其他 shell 很少

> set i = ~/foo/bar.c
> echo ${i:t}
bar.c
> echo ${i:h}
/home/erflungued/foo

Here is something different from above:
Available in tcsh but few other shells AFAIK

> set i = ~/foo/bar.c
> echo ${i:t}
bar.c
> echo ${i:h}
/home/erflungued/foo
无法言说的痛 2024-08-02 08:13:09

我在这里等待答案时发现这样做的方式:

set i = ~/foo/bar.c
echo $i:h

结果:

~/foo

The way I found to do it while waiting for answers here:

set i = ~/foo/bar.c
echo $i:h

result:

~/foo
━╋う一瞬間旳綻放 2024-08-02 08:13:09

完全来说,获取文件名是通过 basename 命令完成的:

set j = `basename ~/foo/bar.c`
echo $j

For completely, getting the file name is accomplished with the basename command:

set j = `basename ~/foo/bar.c`
echo $j
掩耳倾听 2024-08-02 08:13:09
echo $i | awk -F"/" '{$NF="";print}' OFS="/"
echo $i | awk -F"/" '{$NF="";print}' OFS="/"
寒尘 2024-08-02 08:13:09

使用 dirname 命令,例如:

set i = `dirname "~/foo/bar.c"`

注意路径两边的引号。 将它们包括在内很重要。 如果跳过引号,dirname 对于包含空格的路径将失败。 请注意,~/ 表达式在执行dirname 之前计算,因此,如果不使用引号并且主路径包含空格,即使这样简单的示例也可能会失败。

当然,同样的问题也适用于所有其他命令,始终用引号将命令的参数引起来是一个好习惯。

Use dirname command, for example:

set i = `dirname "~/foo/bar.c"`

Notice the quotation marks around path. It's important to include them. If you skip the quotation marks, dirname will fail for paths which contain spaces. Mind that ~/ expression evaluates before dirname is executed, thus even such simple example may fail if quotation marks are not used and home path includes spaces.

Of course the same problem applies also to all other commands, it's good practice to always surround argument to a command with quotation marks.

素衣风尘叹 2024-08-02 08:13:09

确实使用dirname "$i",而不是${i:h}

如果 $i 仅包含文件名(无路径),而 dirname 正确返回当前目录 .,则后者不会产生预期结果。在这种情况下。

> set i = bar.c
> echo ${i:h}
bar.c
> dirname "$i"
.

Use dirname "$i" indeed, and not ${i:h}.

The latter does not produce the intended result if $i contains only a file name (no path), while dirname correctly returns the current directory . in that case.

> set i = bar.c
> echo ${i:h}
bar.c
> dirname "$i"
.
榆西 2024-08-02 08:13:08

如果您的系统提供“dirname”命令,您可以:

set i = `dirname ~/foo/bar.c`
echo $i

注意变量名称前面缺少的 $。 不过,这个解决方案与 shell 无关。

If your system provides a 'dirname' command you could:

set i = `dirname ~/foo/bar.c`
echo $i

Note the missing $ in front of the variable name. This solution is shell agnostic though.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文