使用 powershell 将文本文件中的特定行复制到单独的文件

Jab*_*mal 4 powershell

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

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

我刚刚开始学习powershell,请帮忙

$Clause = Get-Content "Input File location"
$Outvalue = $Clause | Foreach { 
    if ($_ -ilike "*%%*")
    {
        Set-Content "Output file location" $_
    }
}
Run Code Online (Sandbox Code Playgroud)

Tes*_*ler 5

您将循环遍历文件中的行,并将每一行设置为文件的全部内容,每次都会覆盖前一个文件。

您需要切换到 usingAdd-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
Run Code Online (Sandbox Code Playgroud)

您通常会写成:

Get-Content "input.txt" | Where-Object { $_ -like "%%*" } | Set-Content Output.txt
Run Code Online (Sandbox Code Playgroud)

在 shell 中,你可以写成

gc input.txt |? {$_ -like "%%*"} | sc output.txt
Run Code Online (Sandbox Code Playgroud)

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

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


Joã*_*cca 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();
Run Code Online (Sandbox Code Playgroud)