问题
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