如果使用powershell或Javascript在=符號之后一行包含空值,如何洗掉一行?
我的輸入值是
variable1 = value1
variable2 = value2
variable3 =
variable4 = value4
variable5 =
值可能會改變。我正在尋找一個腳本,如果 = 符號后的值為空,則洗掉行。
uj5u.com熱心網友回復:
看起來您正在嘗試更改 .INI 檔案,這樣做實際上可能會破壞某些應用程式初始化..
話雖如此,在 PowerShell 中,您可以執行以下操作:
- 從文本檔案加載時
$result = Get-Content -Path 'X:\theInputFile.txt' | Where-Object { $_ -match '^\w \s*=\s*\S ' }
- 決議多行字串時
$string = @'
variable1 = value1
variable2 = value2
variable3 =
variable4 = value4
variable5 =
'@
$result = $string -split '\r?\n' | Where-Object { $_ -match '^\w \s*=\s*\S ' }
變數$result將是一個字串陣列:
variable1 = value1
variable2 = value2
variable4 = value4
您可以使用
$result | Set-Content -Path 'X:\theNewInputFile.txt'
正則運算式詳細資訊:
^ Assert position at the beginning of the string
\w Match a single character that is a “word character” (letters, digits, etc.)
Between one and unlimited times, as many times as possible, giving back as needed (greedy)
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
= Match the character “=” literally
\s Match a single character that is a “whitespace character” (spaces, tabs, line breaks, etc.)
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\S Match a single character that is a “non-whitespace character”
Between one and unlimited times, as many times as possible, giving back as needed (greedy)
uj5u.com熱心網友回復:
為了補充Theo 的有用答案,它使用基于 cmdlet的流式方法和(純)運算子方法,該方法速度更快,但占用更多記憶體(記憶體使用通常與文本檔案無關):
正如zett42指出的那樣,如果 LHS 運算元(輸入)是一個陣列,則比較運算子(例如)-match充當過濾器,因此您可以將正則運算式直接與行陣列匹配,以獲得匹配行的子陣列:
# Filter the lines of file inputFile.txt by returning only those on which
# "=" is followed by at least one non-whitespace character ("\S"),
# optionally preceded by any number of other characters (".*").
@(Get-Content inputFile.txt) -match '=.*\S'
您可以Get-Content通過添加來加快通話速度-ReadCount 0。
至于何時使用流與純運算子方法:請參閱此答案中有關權衡的部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/358646.html
標籤:javascript 电源外壳
