[英]How to match each line of a text file contents in powershell script
我有一個包含以下內容的文本文件'abc.txt'。
hello_1
你好_2
..
..
hello_n
我需要編寫一個腳本來打開文件abc.txt並讀取每一行,並將每一行存儲在一個名為$ temp的變量中。 我只需要閱讀以“ hello”開頭的行。 以下代碼有什么問題?
我有以下代碼:
foreach ($line in Get-Content "c:\folder\abc.txt")
{
if($line Select-String -Pattern 'hello')
$temp=$line
}
您在$line
之后缺少管道,並且在foreach
之后的整個scriptblock {
和}
中缺少花括號,應為:
foreach ($line in Get-Content "c:\folder\abc.txt")
{
{
if($line | Select-String -Pattern 'hello')
$temp=$line
}
}
另外,我不知道您的目的是什么,但是如果您希望$line
每次都不會被覆蓋,則應該在迭代之外創建一個數組並每次填充它:
所以首先是: $line = @()
而不是$temp=$line
更改為$temp += $line
但是再一次,如果您的全部目的是從文本文件中過濾hello
字符串,那么這應該足夠了:
$temp = (Get-Content "c:\folder\abc.txt") -match '^hello'
嘗試這個 -
$temp = @()
(Get-Content "c:\folder\abc.txt") | % {$temp += $_ | Select-String -Pattern "hello"}
$temp
該代碼將獲取abc.txt
的內容,並為每個對象檢查模式是否與hello
相匹配。 如果匹配,則將相應的值存儲在定義為$temp
的數組中。
要么
您可以這樣改寫原始代碼-
$temp = @()
foreach ($line in Get-Content "c:\folder\abc.txt")
{
if($line | Select-String -Pattern 'hello') {
$temp += line
}
}
在原始代碼中,語句if($line Select-String -Pattern 'hello')
中缺少管道 。 而且您缺少括號 {}
來包含if語句。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.