将与模式匹配的行从文件夹中的所有文本文件提取到单个输出文件 [英] Extract lines matching a pattern from all text files in a folder to a single output file

查看:113
本文介绍了将与模式匹配的行从文件夹中的所有文本文件提取到单个输出文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试提取文件夹中所有文件中以"%%"开头的每一行,然后将这些行复制到单独的文本文件中.当前在PowerShell代码中使用此代码,但未得到任何结果.

I am trying to extract each line starting with "%%" in all files in a folder and then copy those lines to a separate text file. Currently using this code in PowerShell code, but I am not getting any results.

$files = Get-ChildItem "folder" -Filter *.txt
foreach ($file in $files)
{
if ($_ -like "*%%*")
{
Set-Content "Output.txt" 
}  
}

推荐答案

我认为mklement0建议使用Select-String是可行的方法.除了他的答案,您还可以将Get-ChildItem的输出传递到Select-String中,以便整个过程成为Powershell的衬里.

I think that mklement0's suggestion to use Select-String is the way to go. Adding to his answer, you can pipe the output of Get-ChildItem into the Select-String so that the entire process becomes a Powershell one liner.

类似这样的东西:

Get-ChildItem "folder" -Filter *.txt | Select-String -Pattern '^%%' | Select -ExpandProperty line | Set-Content "Output.txt"

这篇关于将与模式匹配的行从文件夹中的所有文本文件提取到单个输出文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆