使用PowerShell从文本文件中复制特定行到单独的文件

4

我正在尝试使用PowerShell从输入文件中获取以%%开头的所有行,并将其粘贴到输出文件中。

我使用了以下代码,但是我只能在输出文件中得到以%%开头的最后一行,而不是所有以%%开头的行。

我刚开始学习PowerShell,请帮忙解决。

$Clause = Get-Content "Input File location"
$Outvalue = $Clause | Foreach { 
    if ($_ -ilike "*%%*")
    {
        Set-Content "Output file location" $_
    }
}
3个回答

5
你正在遍历文件中的每一行,并将每一行内容设置为整个文件的内容,从而每次都会覆盖前面的文件。
你需要切换到使用Add-Content而不是Set-Content,这样可以将内容附加到文件中,或者改变设计方案:
Get-Content "input.txt" | Foreach-Object { 
    if ($_ -like "%%*") 
    {
        $_     # just putting this on its own, sends it on out of the pipeline
    }
} | Set-Content Output.txt

通常情况下,您会这样写:

Get-Content "input.txt" | Where-Object { $_ -like "%%*" } | Set-Content Output.txt

在shell中,你可能会这样写:

gc input.txt |? {$_ -like "%%*"} | sc output.txt

将整个文件进行过滤,然后一次性将所有匹配的行发送到Set-Content中,而不是为每一行分别调用Set-Content。

NB. 默认情况下,PowerShell不区分大小写,因此-like-ilike的行为相同。


5

对于小文件,Get-Content命令很好用。但是如果你尝试在大文件上使用它,Get-Content会占用大量内存,导致程序卡顿。

为了让其他PowerShell初学者更容易理解,我们可以采用更简单的方法来完成这个任务,而且性能更好。所以,类似下面这样的代码就可以胜任:

$inputfile = "C:\Users\JohnnyC\Desktop\inputfile.txt"
$outputfile = "C:\Users\JohnnyC\Desktop\outputfile.txt"

$reader = [io.file]::OpenText($inputfile)
$writer = [io.file]::CreateText($outputfile)

while($reader.EndOfStream -ne $true) {
    $line = $reader.Readline()
    if ($line -like '%%*') {
        $writer.WriteLine($line);
    }
}

$writer.Dispose();
$reader.Dispose();

0
使用 Get-Content 然后使用 Select-String 再然后使用 Select-Content 示例代码:
Get-Content .\File.txt | Select-String 'FindMyText' | Set-Content 'Output.txt'

输出文件:

Output.txt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接