如何在循环中的变量中获取文件名?

时间:2017-01-19 12:25:31

标签: windows batch-file filenames

我想遍历当前目录中的所有.h文件,并为相应的.cpp文件调用批处理函数。实际上我已经有了它的工作,但是当我尝试使用局部变量时,我得到了一些奇怪的输出。

SETLOCAL

for /R  %%f in (*.h) do (
    SET header=%f%
    ECHO header=%header%
    SET source=%%~df%%~pf%%~nf.cpp
    ECHO source=%source%
)

我得到了这个输出:

SETLOCAL

C:\WorkingDirectory>(
SET header=
 ECHO header=
 SET source=C:\WorkingDirectory\SomeFile.cpp
 ECHO source=
)
header=
source=

为什么%%~df%%~pf%%~nf.cpp正确展开,但ECHO %source%什么都不打印?我怎样才能正确SET header=%f%

1 个答案:

答案 0 :(得分:1)

1)您访问的变量不会使用<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sp.androidesp8266wifi"> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".ServiceStatusUpdate"></service> </application> </manifest> 访问%f%

2)正如@npocmaka已经提到的那样,注释%%f是需要的,因为在使用通常的DelayedExpansion时,每个闭合括号的块都会被立即解析。要解决该问题,请在%之后将setlocal EnableDelayedExpansion添加到您的脚本中,并将@echo off更改为%header%!header!也是如此,但循环变量%source%不是这样!

%%f