有时我将Real Name和Author Name都作为此格式的文件夹,如下所示: 真实姓名 - 作者姓名
其他时候我只有一个作者名称作为这种格式的文件夹,如下所示: 作者姓名
我想在存在真实姓名的情况下删除真实姓名和“ - as”并将作者姓名仅设置为变量,或者仅在作者姓名存在时将作者姓名仅设置为该变量如下:AN =%something%
这是我徒劳的尝试:
Studentnameandid
有人可以帮我删除作者姓名并将其设置为变量吗?提前谢谢。
答案 0 :(得分:1)
您的代码
)
放在一个单独的行上,NAME1
代替$
在等号的左侧,用 - as
代替$
,$
定义第二个 FOR 循环的分隔符,如下:
@echo off
SETLOCAL ENABLEEXTENSIONS DISABLEDELAYEDEXPANSION
FOR %%# IN (.) DO (
SET "CF=%%~f#"
SET "NAME1=%%~nx#"
)
SET "AN="
SET "NAME1=%NAME1: - as =$%"
FOR /F "tokens=1* delims=$" %%I in ("%NAME1%") do (
SET "part1=%%I
SET "AN=%%J"
)
IF NOT DEFINED AN SET "AN=%NAME1%"
ECHO AN = %AN%
ENDLOCAL
顺便说一句:最好在上面的代码中使用|
代替$
两次,因为文件夹名称不可能包含竖线字符,而文件夹可能是名字虽然不太可能包含美元符号。
使用子程序的另一种解决方案,可以通过替换
为当前目录中的每个子目录调用for %%# in (.) do call :GetNames "%%~nx#"
例如
for /D %%# in (*) do call :GetNames "%%~nx#"
在下面的评论代码中:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem Run subroutine GetNames with name of current directory without path.
for %%# in (.) do call :GetNames "%%~nx#"
endlocal
goto :EOF
:GetNames
set "FolderName=%~1"
rem Get the string after " - as " which is the author name.
set "AuthorName=%FolderName:* - as =%"
rem If the author name is identical to folder name, then there
rem is not string " - as " included in folder name which means
rem the folder name is the author name.
if "%AuthorName%" == "%FolderName%" (
set "RealName="
goto OutputNames
)
rem Use delayed expansion to remove author name from folder
rem name to get real name in addition to author name.
setlocal EnableDelayedExpansion
set "RealName=!FolderName:- as %AuthorName%=!"
endlocal & set "RealName=%RealName%"
:OutputNames
echo Folder name: %~1
echo Real name: %RealName%
echo Author name: %AuthorName%
goto :EOF
要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。
call /?
echo /?
endlocal /?
for /?
goto /?
if /?
rem /?
set /?
setlocal /?
答案 1 :(得分:1)
@echo off
SETLOCAL
FOR %%a IN (*.*) DO call :GetAuthor "%%~NXa"
goto :EOF
:GetAuthor
set "string=%~1"
set "author="
set "real=%string: - as =" & set "author=%"
if not defined author set "author=%real%"
echo Folder: "%~1"
echo Author: "%author%"
这是一个非常短的程序,不需要额外的解释,因此理解它的最简单方法是删除@echo off
行,执行它并查看代码......
答案 2 :(得分:0)
也许:
@echo off
setlocal enabledelayedexpansion
set "string=Real Name - as Author Name"
for /f "tokens=1,2 delims=-" %%a in ("%string%") do (
set real=%%b
set "real=!real: as =!"
echo !real!
)
endlocal