windows bat批處理腳本 字符串截取、拼接、查找等使用說明

  BAT批處理有着具有非常強大的字符串處理能力,其功能雖沒有C、Python等高級編程語言豐富,但是常見的字符串截取、替換、連接、查找等功能也是應有盡有,本文逐一詳細講解。

1、字符串截取

百學不如一練,直接上字符串截取案例代碼,如下:
vstr1.bat

@echo off & setlocal

rem strlen=31
set str=This is a string function demo.

rem 倒數第5位開始,取4位:demo
echo %str:~-5,4%

rem 倒數第5位開始,取剩餘所有字符:demo.
echo %str:~-5%

rem 倒數第100位開始,返回從0位開始的字符串:This is a string function demo.
echo %str:~-100%

rem 倒數第0位開始,取4位:This
echo %str:~0,4%

rem 倒數第0位開始,取所有字符:This is a string function demo.
echo %str:~0%

rem 倒數第0位開始,取100位超出長度,返回:This is a string function demo.
echo %str:~0,100%

rem 截取字符串賦值給變量
set str1=%str:~0,4%
echo str1=%str1%

rem 顯示系統時間,去掉後面的毫秒顯示
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:武漢=中國%

輸出結果如下:

替換前:str1="This is a string replace demo!"
空格替換成#:str1="This#is#a#string#replace#demo!"

替換前:str2="武漢,加油!"
武漢替換成中國:str2="中國,加油!"

3、字符串連接

較常見編程語言用 + 或 strcat函數 進行字符串拼接而言,bat腳本的字符串連接則更簡單,但是功能也相對較弱,DEMO如下:

@echo off & setlocal

set aa=武漢
set bb=加油
rem 武漢, 加油
echo %aa%, %bb%

rem 武漢, 加油 賦值給aa變量
set "aa=%aa%, %bb%"
echo aa=%aa%
pause

4、字符串查找

字符串查找有兩個命令:find和findstr,簡單理解findstr是find的加強版(除 /C 只顯示匹配到的行數外,其它都可實現),並且支持正則表達式。兩者具體用法可以查看使用說明:find /? 或者 findstr /?,簡單上手可以參考下述DEMO。
vfind_data.txt

Hello, Marcus!
hello, marcus!
Please say hello

rem vfind.bat
@echo off & setlocal
rem vfind_data.txt中查找包含Hello字符串的行,區分大小寫
rem 只找到Hello, Marcus!
find "Hello" vfind_data.txt

rem vfind_data.txt中查找包含Hello字符串的行,不區分大小寫
rem 三行都會找到
find /i "hello" vfind_data.txt

rem vfind_data.txt中查找不包含please字符串的行,不區分大小寫
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字符串的行,區分大小寫
findstr "Hello" vfind_data.txt

rem 查找hello開頭的行,不區分大小寫;數字比較請排除雙引號、空格干擾
findstr /i "^hello" vfind_data.txt

rem 查找hello結尾的行,不區分大小寫;數字比較請排除雙引號、空格干擾
rem 文件最後一行若不是空白行,則最後一行hello$ 匹配不到,字符串查找時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)
發佈了298 篇原創文章 · 獲贊 98 · 訪問量 77萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章