答案1
以下 PowerShell 脚本完全满足您的要求。每个部分都使用相同的文件名和附加的递增数字保存。
## Q:\Test\2018\06\27\SU_1334727.ps1
$FileName = '.\test.txt'
If (Test-Path $FileName){
$File = Get-Item $FileName
(Get-Content $File.FullName -Raw) -Split "(?<=`r?`n *`r?`n)" |
ForEach-Object {$i=1}{
$_ | Set-Content ("{0}_{1}{2}" -f $File.BaseName,$i++,$File.Extension)
}
}
- 该文件被读入为一段连续的文本,并使用正则表达式进行分割,使用后向搜索
示例输出:
> gc .\test_1.txt
1 sf
1 s
1 sg
1 sv
1 sgsv
答案2
有多种方法可以做到这一点,并使用...在网络上进行快速搜索。
Powershell‘按换行分割文件’
…将返回多个结果。
它可以像使用循环和条件使用 New-Item、Get-Children 和 Add-Content cmdlet 一样简单。
$Lines = Get-Content 'D:\Scripts\$data.txt'
New-Item -Path 'D:\Scripts' -Name 'FileName.txt' -ItemType File
$FileName = (Get-ChildItem -Path 'D:\Scripts\FileName.txt').FullName
$FileCount = 0
ForEach($Line in $Lines)
{
If($Line -ne '')
{
'Appending line to a file'
Add-Content -Value $Line -Path $FileName
}
Else
{
'Empty line encountered - creating new file'
$FileName = New-Item -Path 'D:\Scripts' `
-Name (((Get-ChildItem -Path 'D:\Scripts\FileName.txt').BaseName +
($FileCount = $FileCount + 1) + '.txt')) -ItemType File
}
}
Get-ChildItem -Path 'D:\Scripts\filename*'
# Results
Directory: D:\Scripts
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 27-Jun-18 12:48 0 FileName.txt
Appending line to a file
Appending line to a file
Appending line to a file
Empty line encountered - creating new file
Appending line to a file
Appending line to a file
Appending line to a file
Empty line encountered - creating new file
Appending line to a file
Appending line to a file
Appending line to a file
-a---- 27-Jun-18 12:48 21 FileName.txt
-a---- 27-Jun-18 12:48 21 FileName1.txt
-a---- 27-Jun-18 12:48 21 FileName2.txt