我正在尝试使用Powershell从.txt文件获取内容,然后在使用数组过滤数据后设置内容。我看到了很多示例,该示例针对1个单词而不是数组中的任何单词执行此操作。我在这里搜索并尝试采用其他解决方案,但没有任何工作对我有用。我可以在foreach循环中添加些什么来简化此过程?我觉得这将是一个非常简单的答案,而且我过于复杂了。
#Put account numbers into array.
$acctArr = "123456789101","121314151617","181920212223","242526272829"
#Use the array to Output a new NB file that only contains the accounts from the array.
$fileData = (Get-Content -Path "C:\testfile.txt") | Select-String -Pattern $acctArr -SimpleMatch
foreach($item in $fileData){
<# Need code here to figure out how to check the $fileData array for strings in $acctArr
then if a line of the file has one of the numbers in $acctArr let's do a set-content or Out-file of some kind #>
}
编辑:我尝试了solutions from this,但是set-content
似乎设置了整个文件,即使行与$ acctArr中的内容都不匹配
另一个编辑:我也尝试过此操作。我可以写托管$fileData
变量,并将其正确输出到屏幕,但是如果我执行set-content,它不会像我期望的那样写入文件:
$fileData = (Get-Content -Path "C:\Folder\testfile.txt") | Select-String -Pattern $acctArr -SimpleMatch
$fileData | Set-Content Output.txt
答案 0 :(得分:1)
这是一种方法。 [ grin ]它通过获取目标词并将其连接到以竖线分隔的字符串中来构建正则表达式OR。然后它运行-match
,其中输入文件位于运算符的右侧,而正则表达式位于左侧。这样一来,您就能找到与单词列表中一个或多个单词匹配的所有行。
$WordSourceFile = 'C:\Temp\Grouping-Words-List_2019-06-12.log'
$WordCount = 3
$TargetFile = 'C:\Temp\Grouping-Strings-List_2019-06-12.log'
$WordsToFind = Get-Random -Count $WordCount -InputObject (
Get-Content -LiteralPath $WordSourceFile |
Select-Object -SkipLast 3
)
$Regex_WTF = $WordsToFind -join '|'
$InLines = Get-Content -LiteralPath $TargetFile
$OutLines = @($InLines -match $Regex_WTF)
'Words to find = {0}' -f "$WordsToFind"
'Lines in the Target File = {0}' -f $InLines.Count
'Lines in the Output list = {0}' -f $OutLines.Count
'=' * 50
$OutLines
输出...
Words to find = Tejano Taiko Banjo
Lines in the Target File = 1859
Lines in the Output list = 18
==================================================
Banjo
Banjo Bluegrass Guitar
Banjo Bluegrass Guitar Instrumental
Banjo Bluegrass Guitar Instrumental Railroad
Banjo Celtic Instrumental
Banjo Dupe Instrumental
Banjo Female Guitar
Banjo Guitar Rockabilly Rowdy
Banjo Instrumental
Banjo Instrumental Live
Blues Country Guitar Latin Tejano
Country Guitar Latin Tejano
Drum Dupe Instrumental Japanese Taiko
Drum Instrumental Japanese Taiko
Dupe Guitar Latin Rowdy Tejano
Guitar Latin Spanish Tejano
Guitar Latin Tejano
Guitar Tejano
您可以根据需要将$Outlines
保存为CSV或纯文本文件。