AdSense

網頁

2019/11/16

Windows Batch 逐行讀取文字檔案 read text files line by line

在Windows Batch批次檔(bat file)中逐行讀取文字檔的範例。

例如有個文字檔lyrics.txt內容如下。

lyrics.txt

Phum Viphurit - The Art of Detaching One's Heart

Words roaming inside my chest,
'cause, my fucked up head,
belongs to you.
Lost in space, we flew astray,
I'll find my way,
to get to you.
I, thought we were happy.
I, fell out of love.
It's not like before. (May we meet once more.)
Hearts may change, but memories won't,
you know I don't,
I don't want to go.
Was I dreaming of,
the design of love.
if we keep this up,
will we self-destruct?

lyrics.txt同個目錄下建立一個test.bat中使用for迴圈逐行讀取上面文字檔的內容。

test.bat

@echo off

for /f "tokens=*" %%a in (lyrics.txt) do (
  echo %%a
)
pause

/f參數預設只會讀取一行文字中第一個空白字元前的文字然後就會繼續往下一行讀取,所以後面要加上"tokens=*"參數把一行的全部文字讀入變數%%a中。

test.bat執行結果。

Phum Viphurit - The Art of Detaching One's Heart
Words roaming inside my chest,
'cause, my fucked up head,
belongs to you.
Lost in space, we flew astray,
I'll find my way,
to get to you.
I, thought we were happy.
I, fell out of love.
It's not like before. (May we meet once more.)
Hearts may change, but memories won't,
you know I don't,
I don't want to go.
Was I dreaming of,
the design of love.
if we keep this up,
will we self-destruct?
Press any key to continue . . .


參考:

沒有留言:

AdSense