【发布时间】:2014-02-16 22:38:00
【问题描述】:
我有一个包含两列文本的文件。使用批处理文件,我想提取第二列文本并获取字符串长度,然后将字符串长度和字符串文本写入输出文件。挑战我的步骤是确定具有特殊字符的字符串长度。例如,输入文件如下所示:
依他普仑 CN(C)CCC[C@@]1(C2=C(CO1)C=C(C=C2)C#N)C3=CC=C(C=C3)F 布洛芬CC(C)CC1=CC=C(C=C1)C(C)C(=O)O 凯弗莱CC1=C(N2[C@@H]([C@@H](C2=O)NC(=O)[C@@H](C3=CC=CC=C3)N)SC1)C( =O)O 阿司匹林 CC(=O)OC1=CC=CC=C1C(=O)O 亚油酸CCCCC/C=C\C/C=C\CCCCCCCC(=O)O我可以使用批处理命令行和参数 %1 读取提取两个令牌的文件。我已经尝试了一些我在讨论组中找到的子程序,但我无法让它们工作。 “=”符号和其他特殊字符可能会导致问题。我正在寻找一种可以产生类似输出文件的解决方案。忽略“@”、“/”和“\”符号:
依他普仑 49 布洛芬 29 凯弗莱克斯 58 阿司匹林 24 亚油酸 25到目前为止,我的程序如下所示:
@echo off
setLocal EnableDelayedExpansion enableextensions
set arg1=%1
FOR /F "tokens=1,2 delims= " %%r IN (%1) DO (
set teststring="%%s"
echo "Passing " %%s
call :GetStrLength %%s
echo.%%s
goto :EOF
)
::========================
:GetStrLength
setlocal enableextensions
set s=%1
echo " counting.... " %1
:: Get the length of the quoted string assuming a max of 255
set charCount=0
for /l %%c in (0,1,255) do (
set si=!s:~%%c!
if defined si set /a charCount+=1)
if %charCount% EQU 256 set charCount=0
echo The length of "%s%" is %charCount% characters
endlocal & goto :EOF
任何帮助将不胜感激。
【问题讨论】:
-
字符串长度工作正常 - 将参数传递给子程序被破坏。如果您不使用子例程而只是将字符串长度内联会发生什么?
-
尝试只使用
call :GetStrLength "%%s"和set s=%~1以便引用参数 -
@JerryJeremiah 不,您不能以这种方式处理所有可能的字符串,CALL 将按值破坏参数。您需要使用引用。
-
酷 - 微笑字符串。我已经很久没有和那些人一起工作了:-)
标签: string batch-file special-characters readfile string-length