Powershell:通过字符串数组过滤文件的内容 [英] Powershell: Filter the contents of a file by an array of strings

查看:127
本文介绍了Powershell:通过字符串数组过滤文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给我一​​个谜:

我有一个数据文本文件.我想读入它,并且只输出包含在搜索词数组中找到的任何字符串的行.

I have a text file of data. I want to read it in, and only output lines that contain any string that is found in an array of search terms.

如果我只寻找一个字符串,我会这样做:

If I were looking for just one string, I would do something like this:

get-content afile | where { $_.Contains("TextI'mLookingFor") } | out-file FilteredContent.txt

现在,我只需要让TextI'mLookingFor"成为一个字符串数组,如果 $_ 包含数组中的任何字符串,它就会通过管道传递到输出文件.

Now, I just need for "TextI'mLookingFor" to be an array of strings, where if $_ contains any string in the array, it is passed down the pipe to out-file.

我会怎么做(顺便说一句,我是 ac# 程序员,正在破解这个 powershell 脚本,所以如果有比使用 .Contains() 更好的方法来完成我的匹配,请告诉我!)

How would I do that (and BTW, I'm a c# programmer hacking this powershell script, so if there is a better way to do my match above than using .Contains(), clue me in!)

推荐答案

尝试 Select-String .它允许一系列模式.例如:

Try Select-String . It allows an array of patterns. Ex:

$p = @("this","is","a test")
Get-Content '.\New Text Document.txt' | Select-String -Pattern $p -SimpleMatch | Set-Content FilteredContent.txt

请注意,我使用 -SimpleMatch 以便 Select-String 忽略特殊的正则表达式字符.如果您想在模式中使用正则表达式,只需将其删除即可.

Notice that I use -SimpleMatch so that Select-String ignores special regex-characters. If you want regex in your patterns, just remove that.

对于单个模式,我可能会使用它,但您必须在模式中转义正则表达式字符:

For a single pattern I would probably use this, but you have to escape regex characters in the pattern:

Get-Content '.\New Text Document.txt' | ? { $_ -match "a test" }

Select-String 也是一个很好的单一模式的 cmdlet,只是写了几个字符 ^^

Select-String is a great cmdlet for single patterns too, it's just a few characters longer to write ^^

这篇关于Powershell:通过字符串数组过滤文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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