批处理脚本:如何获取没有完整路径的父目录名称?

发布于 2024-12-27 06:20:14 字数 77 浏览 2 评论 0原文

我正在编写一个处理文件夹的脚本,并且其中始终有一个文件需要重命名。新名称应该是父目录名称。如何在批处理文件中获取它?目录的完整路径是已知的。

I'm working on a script that processes a folder and there is always one file in it I need to rename. The new name should be the parent directory name. How do I get this in a batch file? The full path to the dir is known.

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

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

发布评论

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

评论(3

但可醉心 2025-01-03 06:20:14

目前尚不清楚脚本如何熟悉相关路径,但以下示例至少应该让您了解如何继续:

FOR %%D IN ("%CD%") DO SET "DirName=%%~nxD"
ECHO %DirName%

此脚本从 CD 获取路径变量并仅将名称提取到 DirName

It is not very clear how the script is supposed to become acquainted with the path in question, but the following example should at least give you an idea of how to proceed:

FOR %%D IN ("%CD%") DO SET "DirName=%%~nxD"
ECHO %DirName%

This script gets the path from the CD variable and extracts the name only from it to DirName.

澜川若宁 2025-01-03 06:20:14

您可以使用basename命令:

FULLPATH=/the/full/path/is/known
JUSTTHENAME=$(basename "$FULLPATH")

You can use basename command:

FULLPATH=/the/full/path/is/known
JUSTTHENAME=$(basename "$FULLPATH")
烙印 2025-01-03 06:20:14

您可以使用内置的 bash 技巧:

FULLPATH=/the/full/path/is/known
JUSTTHENAME=${FULLPATH##*/}

说明:

  • 第一个 # 表示“从开头删除模式”,
  • 第二个 # 表示“删除较长的 模式”可能的模式'
  • 模式

*/ 是使用内置bash 避免调用外部命令(即basename)的 ,因此这可以优化您的脚本。然而该脚本的可移植性较差。

You can use built-in bash tricks:

FULLPATH=/the/full/path/is/known
JUSTTHENAME=${FULLPATH##*/}

Explanations:

  • first # means 'remove the pattern from the begining'
  • second # means 'remove the longer possible pattern'
  • */ is the pattern

Using built-in bash avoid to call an external command (i.e. basename) therefore this optimises you script. However the script is less portable.

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