我正在編寫一個腳本,它從二進制文件讀取,轉換爲ASCII,提取/分隔2列,並將其輸出到txt。介紹解析循環/重構難看的代碼
我看了this後實現二進制> ASCII步驟,但是,以它在我的腳本中實現的方式,它似乎只對文件中的第一行執行上述過程。
我該如何重寫這個循環遍歷文件中的所有行?
我的代碼如下。
# run the command script to extract the file
script.cmd
# Read the entire file to an array of bytes.
$bytes = [System.IO.File]::ReadAllBytes("filePath")
# Decode first 'n' number of bytes to a text assuming ASCII encoding.
$text = [System.Text.Encoding]::ASCII.GetString($bytes, 0, 999999)|
# only keep columns 0-22; 148-149; separate with comma delimiter
%{ "$($_[$0..22] -join ''),$($_[147..147] -join '')"} |
# convert the file to .txt
set-content path\file.txt
此外,什麼是寫這部分,因此它只是讀取字符串的長度,而不是拉動高達999999個字節的更優雅的方式?
$text = [System.Text.Encoding]::ASCII.GetString($bytes, 0, 999999)|
如果你假設它是ASCII編碼的數據,你爲什麼要讀取它作爲字節,然後轉換爲文本,而不是做ReadAllText開始? – mjolinor
@mjolinor - 文件以二進制形式啓動,然後轉換爲ASCII。我這樣做是因爲我想在腳本的第一步中當我們從FTP拉文件時防止數據損壞。 –
由於它是二進制數據,行如何分隔? – mjolinor