【问题标题】:Powershell - Delete Everything After a Delimiter - In Text files Found in FolderPowershell - 删除分隔符后的所有内容 - 在文件夹中找到的文本文件中
【发布时间】:2016-03-03 19:58:23
【问题描述】:

我想从一堆文本文件中删除内容。

在每个文本文件中 - 删除 ****** 之后的所有内容

$Path = "C:\Users\Desktop\Delete\*.txt"       # Folder Containing Text files  
$OutPath = "C:\Users\Desktop\Files\"    

Get-Content c.txt | Where { $_ -notmatch "*****" } | Set-Content $OutPath

我看过这个powershell delete everything after character for every line in a file

我无法让它工作

我是 Power shell 的新手,请原谅我的代码。

谢谢

【问题讨论】:

    标签: powershell directory


    【解决方案1】:

    您可以使用Get-Content-Delimiter 参数很容易地做到这一点:

    免责声明:未经测试

    $Path = "C:\Users\Desktop\Delete\*.txt"       # Folder Containing Text files  
    $OutPath = "C:\Users\Desktop\Files\"    
    
    Foreach ($file in (Get-Childitem $path))
    {
     (Get-Content $file.fullname -Delimiter '*****')[0] |
      Set-Content "$OutPath\$($file.name)"
     }
    

    【讨论】:

    • 我不敢相信 - 2 行代码将为我节省数小时的手动工作。这真是太棒了。
    【解决方案2】:

    您可以通过将整个文件作为一个字符串读取并使用 -Replace 来使用 RegEx 匹配来做到这一点。

    $OutPath = "C:\Users\Desktop\Files\"
    ForEach($File in Get-ChildItem "C:\Users\Desktop\Delete\*.txt"){
        (Get-Content $File.FullName -Raw) -Replace "(?s)^(.*?\*{5,}).*", '$1' | Set-Content $OutPath + $File.Name
    }
    

    模式匹配解释here

    【讨论】:

    • 谢谢TMD,我很怕正则表达式——我会试试看的:)
    猜你喜欢
    • 2014-06-15
    • 1970-01-01
    • 2020-03-28
    • 2018-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-18
    • 2020-01-02
    相关资源
    最近更新 更多