批处理脚本中如何处理for循环输入里的')'字符?
批处理中提取含特殊字符字符串的最后一个单词
方法一:临时文件中转法
利用延迟扩展将空格替换为换行,通过遍历临时文件的行来获取最后一个单词,避开特殊字符的语法解析问题:
@echo off setlocal enabledelayedexpansion set "_IFLE_input=Left)Close Hello World)" :: 将空格替换为换行符(注意:=^后需手动换行) echo !_IFLE_input: =^ ! > "%temp%\last_word_temp.txt" :: 遍历临时文件的每一行,最终变量值即为最后一个单词 for /f "delims=" %%a in ("%temp%\last_word_temp.txt") do set "_IFLE_last_token=%%a" echo 最后一个单词:!_IFLE_last_token! del "%temp%\last_word_temp.txt" endlocal
方法二:递归字符串替换法
通过循环移除第一个空格及之前的内容,直到字符串中无空格剩余,直接得到最后一个单词:
@echo off setlocal enabledelayedexpansion set "_IFLE_input=Left)Close Hello World)" :trim_loop :: 判断字符串末尾是否为空格,或是否不含空格 if "!_IFLE_input:~-1!"==" " goto trim_done if "!_IFLE_input: =!"=="!_IFLE_input!" goto trim_done :: 移除第一个空格及之前的所有内容 set "_IFLE_input=!_IFLE_input:* =!" goto trim_loop :trim_done set "_IFLE_last_token=!_IFLE_input!" echo 最后一个单词:!_IFLE_last_token! endlocal
两种方法均无需过滤特殊字符,可直接在未更新的Windows 10 22H2自带批处理环境中运行。
内容的提问来源于stack exchange,提问作者Shodan
相关产品推荐
相关产品推荐

