【问题标题】:How do I search a string in powershell and delete the line?如何在 powershell 中搜索字符串并删除该行?
【发布时间】:2015-10-11 15:19:53
【问题描述】:

如果我在一个文本文件中有 5 个单词


red car

yellow flower

purple heart

vault of grass

hard light

我如何搜索单词然后删除它并保存/覆盖...这在 python 中很容易,但 powershell 对我来说有点复杂。

到目前为止,这就是我所拥有的

#name new file
$fileName = read-host "Enter fileName: "

#create new text file to save processes
$textFile = New-Item  C:\Users\socrateslouis\Documents\$folderName\$fileName".txt" -type file

#store in text file
$outfile =Get-Process | Out-File -FilePath C:\Users\socrates\Documents\$folderName\$fileName".txt"
#display processes

$processFile = Get-Content C:\Users\socrates\Documents\$folderName\$fileName".txt"

$processFile

【问题讨论】:

  • 这和python有什么关系?
  • 向我们展示你的 Python 代码,然后
  • 据我所知,您正在将进程列表输出到文本文件。那么你是说你在输出文件中有一个名为“red car”的进程并想要删除它?

标签: python shell powershell scripting powershell-2.0


【解决方案1】:
$File = 'TestFile.txt'
$tempFile = 'TestFileTmp.txt'
$stringToMatch = "vault"

Get-Content $File | Where { $_ -notmatch $stringToMatch } | Set-Content $tempFile
Remove-Item -Path $File
Rename-Item -Path $tempFile -NewName $File -Force

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 2011-09-28
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多