我正在操作一個測驗,我使用多個 .replace 命令來格式化文本。例如
$str="hello%worldZZZniceZZZtoZZZmeet"
$str.Replace("%","`n").replace("ZZZ","`n")
控制臺中的輸出很好,但我需要迭代每一行。問題是 $str.count = 1 意味著即使這個字串在控制臺中顯示良好,powershell 仍將其視為一行。任何的想法?
*** 編輯 *** 如果我將字串輸出到檔案然后讀取它用新行讀取的檔案,但我確定有更好的方法而不是輸出到檔案然后再次讀取它
uj5u.com熱心網友回復:
像你這樣的聲音正在尋找分裂的字串,并得到一個陣列的結果:
$str = "hello%worldZZZniceZZZtoZZZmeet"
$str -split "%|ZZZ"
($str -split "%|ZZZ").count # => 5
由于運算子與正則運算式兼容,因此您可以使用"%|ZZZ"(拆分為%或ZZZ)。
uj5u.com熱心網友回復:
.NET 中的字串是不可變的,這意味著它們總是回傳一個新字串而不是修改當前字串,因此運行后$str.Replace("%","`n").replace("ZZZ","`n")原始字串仍然不變。如果你想處理它,你需要將結果存盤到一個新變數中
PS C:\Users> $newstr = $str.Replace("%","`n").replace("ZZZ","`n")
PS C:\Users> $newstr
hello
world
nice
to
meet
PS C:\Users> $str
hello%worldZZZniceZZZtoZZZmeet
但即便如此,$newstr它仍然是一個沒有任何count方法的字串。我不知道你想做什么count。如果你想獲得變數中的行數,那么只需使用Measure-Object
PS C:\Users> $newstr | Measure-Object -Line
Lines Words Characters Property
----- ----- ---------- --------
5
PS C:\User> ($newstr | Measure-Object -Line).Lines
5
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/393497.html
標籤:电源外壳
