2

I'm trying to find out how to use powershell to find and delete lines without certain string pattern in a set of files. For example, I have the following text file:

111111
22x222
333333
44x444

This needs to be turned into:

22x222
44x444

given that the string pattern of 'x' is not in any of the other lines.

How can I issue such a command in powershell to process a bunch of text files?

thanks.

4

2 回答 2

3
dir | foreach { $out = cat $_ | select-string x; $out | set-content $_  }

dir命令列出当前目录下的文件;foreach遍历每个文件;cat将文件和管道读入select-stringselect-string查找包含特定模式的行,在本例中为“x”;结果select-string存储在$out; 最后,用 .$out写入同一个文件set-content

我们需要临时变量$out,因为您不能同时读取和写入同一个文件。

于 2013-09-14T03:48:03.020 回答
2

这将处理工作目录中的所有 txt 文件。检查每个文件内容,并且只允许传递其中包含“x”的行。结果被写回文件。

Get-ChildItem *.txt | ForEach-Object{
    $content = Get-Content $_.FullName | Where-Object {$_ -match 'x'}
    $content | Out-File $_.FullName
}
于 2013-09-14T09:59:29.097 回答