【问题标题】:Remove a full string of text from a partial string match and not creating a new file从部分字符串匹配中删除完整的文本字符串而不创建新文件
【发布时间】:2017-06-04 20:04:27
【问题描述】:

我目前正在尝试从多个文件中删除部分匹配的完整文本字符串。

例如,我有一个页眉和一个页脚,其中字符 0*5 的顺序完全相同。我想在不更改文件名的情况下从特定文件夹中的文件中完全删除页眉和页脚。我已经找到并尝试了服务器 Get-Content myFile.txtSet-Content newFile.txt

我的文件位于一个文件夹中,所以我从“*”中调用它们。他们都有不同的名字。我正在尝试通过 PowerShell 一次性删除所有页眉和页脚。

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    我不喜欢丢失原件,所以我使用 long 方法:

    $ListofFiles = Get-ChildItem c:\windows\logs\* -include *.txt
    
    ForEach ($item in $ListOfFiles){
        $FileContent = Get-Content "$item.txt"
        Rename-Item -path "c:\windows\logs\$item.txt" -newname "$item.old"
        ForEach ($line in $FileContent) {
            If ($Line -like "*whatever i am looking for*") {
                Write-host "Found the entry i was looking for"
            }
            else {
                $Line | Out-File "c:\windows\logs\$item.txt"
            }
        }
    }
    

    【讨论】:

    • 您的$item 字符串中有一个错误 - 单引号字符串不会插入变量,因此您将始终将$item.txt 作为文字文件名而不是循环变量内容来读写.txt
    • 感谢您指出这一点......当我将其粘贴到所有双引号的地方......
    猜你喜欢
    • 1970-01-01
    • 2020-03-27
    • 2011-06-17
    • 1970-01-01
    • 2014-12-19
    • 2015-09-06
    • 2017-05-26
    • 2021-06-24
    相关资源
    最近更新 更多