2016-03-03 49 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

相关问题