bat 批处理之字符串操作

来源:互联网 发布:java web框架排行 编辑:程序博客网 时间:2024/06/08 08:52

  • 对于字符串的截取
  • 字符串的替换
  • 字符串合并
  • 字符串查找
  • bat 批处理代码
  • 相应的运行结果

通常情况下,任何一种语言对于字符串的操作都是重中之重。这里稍微介绍下bat批处理中对于字符串的操作。

对于字符串的截取

set testStr=abcdefghijklmnopqrstuvwxyz0123456789echo 原始字符串 %testStr%echo 提取前五个字符串:%testStr:~0,5%echo 提取最后五个字符串:%testStr:~-5%echo 提取第一个到倒数第六个字符串:%testStr:~0,-5%echo 提取五个字符串,从第四个字符开始:%testStr:~3,5%

字符串的替换

echo 替换之前:%repStr%echo 替换后:%repStr:aa=zz%echo repStr=%repStr%set "repStr=%aa:aa=zz%"echo repStr=%repStr%

字符串合并

set aa=aabbccset bb=ddeeffecho %aa%%bb%echo aa=%aa%echo bb=%bb%set "aa=%aa%%bb%"echo aa=%aa%

字符串查找

Setlocal ENABLEDELAYEDEXPANSION::启用命令扩展,参加setlocal /?命令set str1=This is a test stringset ch1=t::注意,这里是区分大小写的!set str=%str1%::复制字符串,用来截短,而不影响源字符串:nextif not "%str%"=="" (set /a num+=1if "!str:~0,1!"=="%ch1%" goto last::比较首字符是否为要求的字符,如果是则跳出循环set "str=%str:~1%"goto next)set /a num=0::没有找到字符时,将num置零:lastecho 字符'%ch1%'在字符串"%str1%"中的首次出现位置为%num%echo 输出完毕,按任意键退出&&pause>nul&&exit

这里直接贴上对应的bat批处理代码及其运行结果

bat 批处理代码

echo offecho 完全路径:%0echo 去掉引号:%~0echo 所在分区:%~d0echo 所在路径:%~p0echo 文件名:%~n0echo 拓展名:%~x0echo 文件属性:%~a0echo 修改时间:%~t0echo 文件大小:%~z0echo %d0%echo dp0 : %~dp0echo sdp0:%~dp0echo fo:%~f0echo cd %cd%rem set 目标字符串=%源字符串:~起始值,截取长度%set testStr=abcdefghijklmnopqrstuvwxyz0123456789echo 原始字符串 %testStr%echo 提取前五个字符串:%testStr:~0,5%echo 提取最后五个字符串:%testStr:~-5%echo 提取第一个到倒数第六个字符串:%testStr:~0,-5%echo 提取五个字符串,从第四个字符开始:%testStr:~3,5%echo ================================================echo ================    字符串替换       ===========echo ================================================set repStr=aaabbbcccdddeeefffecho 替换之前:%repStr%echo 替换后:%repStr:aa=zz%echo repStr=%repStr%set "repStr=%aa:aa=zz%"echo repStr=%repStr%echo ================================================echo ================    字符串合并       ===========echo ================================================set aa=aabbccset bb=ddeeffecho %aa%%bb%echo aa=%aa%echo bb=%bb%set "aa=%aa%%bb%"echo aa=%aa%Setlocal ENABLEDELAYEDEXPANSION::启用命令扩展,参加setlocal /?命令set str1=This is a test stringset ch1=t::注意,这里是区分大小写的!set str=%str1%::复制字符串,用来截短,而不影响源字符串:nextif not "%str%"=="" (set /a num+=1if "!str:~0,1!"=="%ch1%" goto last::比较首字符是否为要求的字符,如果是则跳出循环set "str=%str:~1%"goto next)set /a num=0::没有找到字符时,将num置零:lastecho 字符'%ch1%'在字符串"%str1%"中的首次出现位置为%num%echo 输出完毕,按任意键退出&&pause>nul&&exit

相应的运行结果

运行结果

原创粉丝点击