本帖最后由 wxyz0001 于 2021-5-19 13:48 编辑
- $TextToAdd="## "
- $Pattern="上一篇"
- $filePath="E:\news"
- $Filter="*.txt"
- $newPath="D:\newtxt"
- If(!(test-path $newPath)){md D:\newtxt}
- Get-ChildItem -Path $filePath -Filter $Filter|ForEach-Object{
- $line=0
- $temppath=$newPath+"\"+$_.name
- $lastIndex=(get-content $_.FullName)|Select-String -Pattern $Pattern
- $fileData=(get-content $_.FullName)[2..($lastIndex.LineNumber -2)]|ForEach-Object{
- $line++
- if($line -lt 2){$TextToAdd+$_}
- elseif($line -ge 2){$_}
- }|out-file $temppath -Encoding utf8
- }
复制代码 上面是以前的代码,经过一段时间对Powershell的摸索,下面的代码用正则表达式简化了不少
#▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇- $match="(?<=^.*\n.*\n)([\s\S]*)(?=上一篇)"
- $filePath="E:\news"
- Get-ChildItem $filePath -Filter "*.txt"|ForEach-Object{
- if([string](Get-Content $_|Out-String) -match $match)
- {
- '##'+$($matches[1])|out-file -append $filePath\a.txt
- }
- }
复制代码
|