[英]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.