??BAT批處理有著具有非常強(qiáng)大的字符串處理能力,其功能雖沒有C、Python等高級(jí)編程語言豐富,但是常見的字符串截取、替換、連接、查找等功能也是應(yīng)有盡有,本文逐一詳細(xì)講解。
百學(xué)不如一練,直接上字符串截取案例代碼,如下: vstr1.bat
@echo off & setlocal
rem strlen=31
set str=This is a string function demo.
rem 倒數(shù)第5位開始,取4位:demo
echo %str:~-5,4%
rem 倒數(shù)第5位開始,取剩余所有字符:demo.
echo %str:~-5%
rem 倒數(shù)第100位開始,返回從0位開始的字符串:This is a string function demo.
echo %str:~-100%
rem 倒數(shù)第0位開始,取4位:This
echo %str:~0,4%
rem 倒數(shù)第0位開始,取所有字符:This is a string function demo.
echo %str:~0%
rem 倒數(shù)第0位開始,取100位超出長(zhǎng)度,返回:This is a string function demo.
echo %str:~0,100%
rem 截取字符串賦值給變量
set str1=%str:~0,4%
echo str1=%str1%
rem 顯示系統(tǒng)時(shí)間,去掉后面的毫秒顯示
echo %time:~0,8%
2、字符串替換
替換字符串,即將某一字符串中的特定字符或字符串替換成指定的字符串,DEMO如下: vstr2.bat
@echo off & setlocal
set str1="This is a string replace demo!"
echo 替換前:str1=%str1%
echo 空格替換成#:str1=%str1: =#%
echo=
set str2="武漢,加油!"
echo 替換前:str2=%str2%
echo 武漢替換成中國:str2=%str2:武漢=中國%
輸出結(jié)果如下:
替換前:str1="This is a string replace demo!"
空格替換成#:str1="This#is#a#string#replace#demo!"
替換前:str2="武漢,加油!"
武漢替換成中國:str2="中國,加油!"
3、字符串連接
較常見編程語言用 + 或 strcat函數(shù) 進(jìn)行字符串拼接而言,bat腳本的字符串連接則更簡(jiǎn)單,但是功能也相對(duì)較弱,DEMO如下:
@echo off & setlocal
set aa=武漢
set bb=加油
rem 武漢, 加油
echo %aa%, %bb%
rem 武漢, 加油 賦值給aa變量
set "aa=%aa%, %bb%"
echo aa=%aa%
pause
4、字符串查找
字符串查找有兩個(gè)命令:find和findstr,簡(jiǎn)單理解findstr是find的加強(qiáng)版(除 /C 只顯示匹配到的行數(shù)外,其它都可實(shí)現(xiàn)),并且支持正則表達(dá)式。兩者具體用法可以查看使用說明:find /? 或者 findstr /?,簡(jiǎn)單上手可以參考下述DEMO。 vfind_data.txt
Hello, Marcus!
hello, marcus!
Please say hello
rem vfind.bat
@echo off & setlocal
rem vfind_data.txt中查找包含Hello字符串的行,區(qū)分大小寫
rem 只找到Hello, Marcus!
find "Hello" vfind_data.txt
rem vfind_data.txt中查找包含Hello字符串的行,不區(qū)分大小寫
rem 三行都會(huì)找到
find /i "hello" vfind_data.txt
rem vfind_data.txt中查找不包含please字符串的行,不區(qū)分大小寫
rem 找到hello 開頭的兩行
find /v /i "please" vfind_data.txt
rem 字符串作為輸入,查找該字符串中是否包含“hello”
rem 輸出Hello, marcus!
echo Hello, marcus! | find /i "hello"
rem vfindstr.bat
@echo off & setlocal
rem 查找文件vfind_data.txt中包含Hello字符串的行,區(qū)分大小寫
findstr "Hello" vfind_data.txt
rem 查找hello開頭的行,不區(qū)分大小寫;數(shù)字比較請(qǐng)排除雙引號(hào)、空格干擾
findstr /i "^hello" vfind_data.txt
rem 查找hello結(jié)尾的行,不區(qū)分大小寫;數(shù)字比較請(qǐng)排除雙引號(hào)、空格干擾
rem 文件最后一行若不是空白行,則最后一行hello$ 匹配不到,字符串查找時(shí)hello$也匹配不到
findstr /i "hello$" vfind_data.txt
echo Hello, marcus! | findstr /i "hello"
rem 找到輸出found,沒找到輸出not found
echo Hello, marcus! | findstr /i "hello" > nul && (echo found) || (echo not found)
|