[英]How to match each line of a text file contents in powershell script
I have a text file 'abc.txt' that contains the below. 我有一个包含以下内容的文本文件'abc.txt'。
hello_1 hello_1
hello_2 你好_2
.. ..
.. ..
hello_n hello_n
I need to write a script to open the file abc.txt and read each line and store that each line in a variable called $temp. 我需要编写一个脚本来打开文件abc.txt并读取每一行,并将每一行存储在一个名为$ temp的变量中。 I need to read the line only that starts with 'hello'. 我只需要阅读以“ hello”开头的行。 What is wrong with the below code? 以下代码有什么问题?
I have the below Code: 我有以下代码:
foreach ($line in Get-Content "c:\folder\abc.txt")
{
if($line Select-String -Pattern 'hello')
$temp=$line
}
You missing pipeline after $line
, and curly braces are missing in the whole scriptblock {
and }
after the foreach
, should be: 您在$line
之后缺少管道,并且在foreach
之后的整个scriptblock {
和}
中缺少花括号,应为:
foreach ($line in Get-Content "c:\folder\abc.txt")
{
{
if($line | Select-String -Pattern 'hello')
$temp=$line
}
}
Also, I don't know what is your purpose, but if you want $line
will not be overwrited each time you should create an array outside of the iterration and fill it each time: 另外,我不知道您的目的是什么,但是如果您希望$line
每次都不会被覆盖,则应该在迭代之外创建一个数组并每次填充它:
so first is: $line = @()
and instead of $temp=$line
change to $temp += $line
所以首先是: $line = @()
而不是$temp=$line
更改为$temp += $line
But then again if all your purpose is to filter the hello
string from the text file then this should be enough: 但是再一次,如果您的全部目的是从文本文件中过滤hello
字符串,那么这应该足够了:
$temp = (Get-Content "c:\folder\abc.txt") -match '^hello'
Try this - 尝试这个 -
$temp = @()
(Get-Content "c:\folder\abc.txt") | % {$temp += $_ | Select-String -Pattern "hello"}
$temp
The code is getting the content of abc.txt
, and for each object checking if the pattern matches hello
. 该代码将获取abc.txt
的内容,并为每个对象检查模式是否与hello
相匹配。 If it's a match, then it stores the corresponding value in the array defined as $temp
. 如果匹配,则将相应的值存储在定义为$temp
的数组中。
OR 要么
You can rephrase your original code like this - 您可以这样改写原始代码-
$temp = @()
foreach ($line in Get-Content "c:\folder\abc.txt")
{
if($line | Select-String -Pattern 'hello') {
$temp += line
}
}
In you original code, you are missing a pipeline in the statement if($line Select-String -Pattern 'hello')
. 在原始代码中,语句if($line Select-String -Pattern 'hello')
中缺少管道 。 And you are missing braces {}
to enclose the if statement. 而且您缺少括号 {}
来包含if语句。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.