2016-03-03 40 views
1

我想從一堆文本文件中刪除內容。Powershell - 刪除分隔符後的所有內容 - 在文件夾中的文本文件中找到

在每個文本文件 - 刪除一切後,******

$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

我無法得到它的工作

我是新手與電源殼請原諒我的代碼。

謝謝

回答

2

您可以使用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)" 
} 
+0

我不敢相信 - 兩行代碼可以節省我幾個小時的手動工作。這非常棒。 – wp44

+0

先生們感謝您的幫助 – wp44

1

你可以用正則表達式匹配做到這一點:

免責聲明整個文件作爲一個字符串,並使用-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 
} 

模式匹配解釋here

+0

謝謝TMD,我非常害怕正則表達式 - 我會試試看:) – wp44

相關問題