2011-10-16

批次處理程序的字串功能 (Function of String in Batch)

Windows 擁有優良的界面控制,但如果涉及大量重覆性的運作
使用界面並不合適,因此便需要使用批次處理程序
Windows provides a good quality of GUI, but, if you would like to do a large number of repetitive operations,
GUI is not appropriate, so we need to use the batch process

Windows 的 Batch File 與 Unix/Linux 的 Shell Script 很相似
但在功能上 Batch File 比 Shell Script 弱
而且使用限制亦相當大,說明文件亦比較難理解
Batch File in Windows and Shell Script in Unix/Linux is similar.
However, the syntax of Batch File is weaker than Shell Script
and restrictions are quite large, the documentation is also more difficult to understand.

在 Batch File 經常使用的形態是字串
String is the most usable type in Batch File
set string=mystring
這是一個簡單的語法將字串「mystring」指派至變數「string」
This is a simple statement to assign "mystring" to variable "string"
echo %string%
echo 是將資料輸出至命令提示字元的指令
被 % 前後包著的文字便是變數名稱
echo is a command to show the message on console
A text wrapped by % is a variable name

截取字串
Get a substring
set string=mystring
echo %string:~0,2%
0 表示開始位置,第一個字符位置為 0
2 表示截取字串長度
開始位置必須為整數,截取字串長度必須為正整數
當開始位置為負數時,會倒向截取如 %string:~-3,2% 傳回「in」
不使用截取字串長度或截取長度大於字串長度時,便從開始位置截取至最後如 %string:~4% 傳回「ring」
0 is the start index, the index of first letter is 0
2 is the length of substring
start index must be integer, length of substring must be positive integer
If the start index is negative integer, it will intercept the substring reversely, for example %string:~-4,2% returns "in"
If you don't use length of substring or length of substring is larger than length of original string, it will intercept the substring from start index to end of original string, for example %string:~4% returns "ring"

字串取代
String replacement
set string=herro
echo %string:r=l%
r 為搜尋的字串,不能是空字串
l 為取代的字串
如例子會傳回「hello」
r is the search string, it cannot be empty string
l is the replace string
The example returns "hello"

字串長度
Length of string
Batch File 並沒有計算字串長度的方法,所以必須由使用者自行編制計算器
由於沒有正式的計算字串長度的方法,因此動用了: if defined , labal , goto 來模擬
Batch File does not have a method to calculate the length of string, so user must write a sub-routine to count the length of string
There is not regular method to calculate the length of string, so we use: if defined, label, goto to simulate
set string=mystring
set /a length=0
:loop
if defined string (
    set string=%string:~1%
    set /a length+=1
    goto loop
)
echo %length%

3 則留言 :

  1. 請教一下,若計算字串長度,字串中含有空白,要怎麼解決?
    如my string,這樣只會計算到my。

    回覆刪除
    回覆
    1. 可以在 set variable 的時候用雙引號框起來,例如 set "string=my string"
      這樣計算出來的長度會把空白也算進去,"my string" 長度 = 9

      刪除
  2. 你好,請問如何對batch的字串,以指定位置做取代

    回覆刪除