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.
Asked
Active
Viewed 3,596 times
3 Answers
5
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
.

Andriy M
- 76,112
- 17
- 94
- 154
-
1to properly cope with folder names that contain a dot `.` in its name, you should use `%%~nxD` instead – PA. Jan 17 '12 at 06:39
-1
You can use basename
command:
FULLPATH=/the/full/path/is/known
JUSTTHENAME=$(basename "$FULLPATH")

oHo
- 51,447
- 27
- 165
- 200
-1
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.

oHo
- 51,447
- 27
- 165
- 200
-
I don't know how to implement that. looks like a bit over my expertiese (not any acceptable commands I'm aware of) I need a little walkthrough – cafevincent Jan 16 '12 at 15:24
-
@cafevincent Please give an example of what you have: What is your directories, your files; Do you require one line command or do you require to modify a script? You say "The full path to the dir is known" => what is the variable name? – oHo Jan 17 '12 at 12:39
-