batch scripting: how to get parent dir name without full path?

我怕爱的太早我们不能终老 提交于 2019-12-23 22:20:04

问题


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.


回答1:


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.




回答2:


You can use basename command:

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



回答3:


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.



来源:https://stackoverflow.com/questions/8871385/batch-scripting-how-to-get-parent-dir-name-without-full-path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!