Powershell - Delete Everything After a Delimiter - In Text files Found in Folder

China☆狼群 提交于 2021-02-11 11:53:00

问题


I would like to delete content from a bunch of text files.

In each text file - Delete Everything After the ******

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

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

I have seen this powershell delete everything after character for every line in a file

I couldn't get it to work

I am a newbie with power shell do please forgive my code.

Thank you


回答1:


You can use the -Delimiter parameter of Get-Content to do this pretty easily:

Disclaimer: not tested

$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:


You could do this with a RegEx match by reading the whole file as one string, and using -Replace.

$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
}

Pattern match explained here.



来源:https://stackoverflow.com/questions/35781809/powershell-delete-everything-after-a-delimiter-in-text-files-found-in-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!