我有一個名為 notification.txt 的檔案,其中包含我需要修剪的資料并將修剪后的輸出傳遞給另一個命令。
檔案是隨機的行數,可以是 1,也可以是 100 ,它們看起來像這樣:
hostname.domain.xyz Notification
hostname.domain.xyz Notification
hostname.domain.xyz Notification
hostname.domain.xyz Notification
我正在尋找從第一個.到右邊的所有內容,它只會將主機名留在一個陣列/變數中,然后我可以使用它傳遞給另一個命令。
uj5u.com熱心網友回復:
您可以在第一次出現后洗掉所有內容,方法.是呼叫Split并丟棄除第一部分之外的所有內容:
$strings = @(
'host1.domain.tld Notification'
'host2.domain.tld Notification'
'host3.domain.tld Notification'
'host4.domain.tld Notification'
'host5.domain.tld Notification'
)
$hostnames = $strings |ForEach-Object { $_.Split('.')[0] }
$_.Split('.')回傳一個字串陣列(例如@('host1','domain','tld Notification')),并[0]為我們提供所述陣列中的第一個元素
或者,使用-replace正則運算式運算子:
$hostnames = $strings -replace '\..*$'
正則運算式模式\..*$將匹配第一個文字點.及其之后的所有內容,直到字串的結尾,并且由于我們使用-replace沒有替代字串的運算子作為第二個引數,因此整個部分都將被洗掉。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/416698.html
標籤:
