使用Powershell删除文本文件中存在的短语列表

使用Powershell删除文本文件中存在的短语列表,powershell,Powershell,我正在尝试使用一个超过100个短语的列表,我想从文本文件products.txt中删除这些短语,其中包含多行文本,每行以制表符分隔/换行。这样,与短语列表不匹配的结果将重新写入当前文件 #cd .\Desktop\ $productlist = @( 'example', 'juicebox', 'telephone', 'keyboard', 'manymore') foreach ($product i

我正在尝试使用一个超过100个短语的列表,我想从文本文件products.txt中删除这些短语,其中包含多行文本,每行以制表符分隔/换行。这样,与短语列表不匹配的结果将重新写入当前文件

#cd .\Desktop\
$productlist = @(
        'example',
        'juicebox',
        'telephone',
        'keyboard',
        'manymore')
    
foreach ($product in $productlist) {
    
get-childitem products.txt | Select-String -Pattern $product -NotMatch | foreach {$_.line} | Out-File -FilePath .\products.txt
    
}
上面的代码没有删除$productlist中列出的单词,它只是再次输出products.txt中的所有链接

products.txt文件中的行如下所示:

productcatalog
product1example
juicebox038
telephoneiphone
telephoneandroid
randomitem
logitech
coffeetable
razer

谢谢你的帮助。

这里有一种方法可以满足你的需要。这比你用的更直接一些。[grin]它采用的方式是,当PoSh位于操作员左侧时,它可以对整个集合进行操作

它的作用

假装在文本文件中阅读 当准备在现实生活中这样做时,用获取内容的调用替换整个region/endregion块。 生成排除列表 将其转换为正则表达式或模式 筛选出与不需要的列表匹配的项目 显示结果列表 代码

#region >>> fake reading in a text file
#    when ready to do this for real, replace the whole "#region/#endregion" block with a call to Get-Content
$ProductList = @'
productcatalog
product1example
juicebox038
telephoneiphone
telephoneandroid
randomitem
logitech
coffeetable
razer
'@ -split [System.Environment]::NewLine
#endregion >>> fake reading in a text file

$ExcludedProductList = @(
        'example'
        'juicebox'
        'telephone'
        'keyboard'
        'manymore'
        )
$EPL_Regex = $ExcludedProductList -join '|'

$RemainingProductList = $ProductList -notmatch $EPL_Regex

$RemainingProductList
输出

productcatalog
randomitem
logitech
coffeetable
razer

这是我的解决办法。您需要括号,否则输入文件将在尝试写入文件时被使用。selectstring接受一个模式数组。我希望我可以通过管道“路径”来设置内容,但它不起作用

$productlist = 'example', 'juicebox', 'telephone', 'keyboard', 'manymore'

(Select-String $productlist products.txt -NotMatch) | % line |
  set-content products.txt

你试过在一行上替换文本吗?您的代码似乎没有进行任何类型的替换。//请添加Products.txt文件的示例,以便大家了解如何构造查找和替换。@Lee_Dailey我更新了问题,使其包含Products.txt文件的内容。这一部分选择字符串选择字符串模式$product-NotMatch获取列表中不存在的行,然后添加到products.txt文件中。我是新加入Powershell的,我关注了MS文档。感谢您提供更多信息!我设法误解了你的意图。。。如果行与任何产品列表项匹配,则要删除整行。您的问题似乎是您从同一个文件读取然后写入的方式。你试过写入其他文件吗?@Lee_Dailey没问题!:是的,即使更改和添加了一个新文件,如like Out file-FilePath。\FormattedProducts.txt仍然没有更改相同的结果所有列表都显示为输入的列表请查看我发布的答案。它似乎可以按照您的意愿工作。谢谢您,Lee,代码完全有道理,但出于某种原因,它显示了products.txt中的所有列表,并在最后显示了一行。如果每个短语前面都有字符或其他单词,比如www.logitech.com,因为有短语logitech,那么正则表达式会起作用吗?是吗?@RonaldLexburg-如果你运行我发布的代码,结果是否与我显示的一样?