簡體   English   中英

Powershell 寫入文件維護結構的腳本

[英]Powershell script to write to file maintaining structure

我正在使用 powershell 讀取文件。 請參閱文件中的示例內容。

This is my file with content
-- #Start
This is more content
across different lines
etc etc
-- #End

我正在使用此代碼將文件讀入變量。

$content = Get-Content "Myfile.txt";

然后,我使用此代碼根據開始和結束標記從文件中刪除特定部分。

$stringBuilder = New-Object System.Text.StringBuilder;
$pattern = "-- #Start(.*?)-- #End";
$matched = [regex]::match($content, $pattern).Groups[1].Value; 
$stringBuilder.AppendLine($matched.Trim());
$stringBuilder.ToString() | Out-File "Newfile.txt" -Encoding utf8;

我遇到的問題是在我寫入的文件中,格式沒有得到維護。 所以我想要的是:

This is more content
across different lines
etc etc

但我得到的是:

This is more content across different lines etc etc

有什么想法可以改變我的代碼,以便在輸出的文件中保持結構(多行)?

這個正則表達式可能會做你正在尋找的東西,在這種情況下看不到使用StringBuilder的意義。 請注意,因為這是一個多行正則表達式模式,您需要使用-Raw開關來讀取文件的內容。

$re = [regex] '(?ms)(?<=^-- #Start\s*\r?\n).+?(?=^-- #End)'
$re.Match((Get-Content path\to\Myfile.txt -Raw)).Value |
    Set-Content path\to\newFile.txt -NoNewLine

詳見https://regex101.com/r/82HJxf/1


如果要逐行處理,可以使用switch來讀取和處理感興趣的行。 如果文件很大並且不適合 memory,這將特別有用。

& {
    $capture = $false
    switch -Rege -File path\to\Myfile.txt {
        '^-- #Start' { $capture = $true }
        '^-- #End' { $capture = $false }
        Default { if($capture) { $_ } }
    }
} | Set-Content path\to\newFile.txt

如果開始和結束標簽只有一次出現,你甚至可以在遇到結束標簽時立即break開關以停止處理:

'^-- #End' { break }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM