[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖
本帖最后由 aloha20200628 于 2023-11-27 18:00 编辑


一。不写一堆纯P代码,就要用其他手段代劳。系统原装的 jscript 或外部资源如 python、sed.exe 等可以逐步简化一楼示例的解法》
以下6行代码存为批处理脚本运行》cmd+jscript混编
  1. @set @v=1 /*
  2. @echo off
  3. for /f "delims=" %%F in ('dir/b/s/a-d *.txt') do (type "%%~F"|cscript /e:javascript "%~f0">"%%~F.new")
  4. exit/b
  5. */
  6. lines=WSH.stdin.readall().replace(/#[^#]*#/g, ''); WSH.echo(lines);
复制代码
以下5行代码存为批处理脚本运行》假设系统已经预装python
  1. @echo off
  2. for /f "delims=" %%F in ('dir/b/s/a-d *.txt') do (
  3. type "%%~F"|python -c "import sys,re;s=sys.stdin.read();print(re.sub('#[^#]*#','',s,re.S))">"%%~F.new"
  4. )
  5. exit/b
复制代码
以下2行代码存为批处理脚本运行》假设sed.exe已被下载安装在系统路径
  1. @echo off &for /f "delims=" %%F in ('dir/b/s/a-d *.txt') do (sed "s/#[^#]*#//g" "%%~F">"%%~F.new")
  2. exit/b
复制代码
二。再给一段纯P代码》未发现内置的字符串操作捷径,只能用纯P的基本方法,先获取字符串长度再逐字判断以求目标结果... 此法虽然基本但确有灵活性,可有多种字符串处理用途。
以下代码存为批处理脚本运行》
  1. @echo off &setlocal enabledelayedexpansion
  2. for /f "delims=" %%F in ('dir/b/s/a-d *.txt') do (
  3. (for /f "usebackq delims=" %%s in ("%%~F") do (
  4. set "cut=-1" &set "_s=" &set "s=%%~s" & (call :_strLen s sl)
  5. for /L %%i in (0,1,!sl!) do (
  6. set "c=!s:~%%i,1!"
  7. if "!c!" neq "#" (if !cut! equ -1 set "_s=!_s!!c!") else (set/a "cut=0-!cut!")
  8. )
  9. echo,!_s!
  10. ))>"%%~F.new"
  11. )
  12. endlocal&exit/b
  13. :_strLen //获取字符串长度 %1=被测字符串变量名 %2=返回值变量名
  14.    set "_str=!%~1!" &set "Len=0"
  15.    for %%n in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
  16.         if "!_str:~%%n,1!" neq "" (set/a "Len+=%%n"&set "_str=!_str:~%%n!")
  17.    )
  18.    set/a "%~2=%Len%" &exit/b
复制代码
1

评分人数

    • 77七: 感谢分享技术 + 1

TOP


订正了15楼代码。其中jscript和python脚本因均以文件而非行作为处理单位,故可有效解析定界符内容被断行的情况。

TOP

本帖最后由 aloha20200628 于 2023-11-28 14:25 编辑


一楼示例中没有那些 ^&!%()<\|/> 等特殊字符作祟,故15楼的纯P代码可以应付,当然 jscript/python/sed 等解决方案可以对此无惧。
若真要考虑纯P解法能处理上述特殊字符,还须订正其中的代码(包括字符串长度获取函数)如下》

按一楼示例原意顺便改写一个包含特殊字符的测试样本 test.txt:
'~^&!%(#将被删除#)<\|/>
'~^&!%()<\|/>#将被删除#
#将被删除#'~^&!%()<\|/>
  1. @echo off
  2. for /f "delims=" %%F in ('dir/b/s/a-d *.txt') do (
  3. (for /f "usebackq delims=" %%s in ("%%~F") do (
  4. set s=%%~s
  5. setlocal enabledelayedexpansion
  6. set "cut=-1" &set "_s=" &(call :_strLen s sL)
  7. for /L %%i in (0,1,!sL!) do (
  8. set "c=!s:~%%i,1!"
  9. if "!c!" neq "#" (if !cut! equ -1 set "_s=!_s!!c!") else (set/a "cut=0-!cut!")
  10. )
  11. (echo,!_s!)
  12. endlocal
  13. ))>"%%~F.new"
  14. )
  15. endlocal &exit/b
  16. :_strLen //获取字符串长度(须先开启变量延迟可保全^!等特殊字符) %1=被测字符串变量名 %2=返回值变量名
  17. set "_str=_!%~1!" &set "Len=0"
  18. for %%n in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
  19. if "!_str:~%%n,1!" neq "" (set/a "Len+=%%n"&set "_str=!_str:~%%n!")
  20. )
  21. set/a "%~2=!Len!-1" &exit/b
复制代码

TOP

返回列表