Board logo

标题: [文本处理] 求教!批处理拆分txt文件 [打印本页]

作者: 爱琴海不会走    时间: 2019-3-7 16:51     标题: 求教!批处理拆分txt文件

在文件夹下,有 原始.txt,想要将原始.txt进行拆分,拆分成多个txt文件,原始.txt内容如下:
  1. [属性描述]
  2. 格式版本号=1.01版本
  3. 数据产生单位=XX公司
  4. 数据日期=2019-01-26
  5. [地块坐标]
  6. 4,324.9,LY61082101-36(19),有易镇燕峁村,面,J49G024040、J49G024041,旱地、灌木林地、其他林地、天然牧草地,013、032、033、041,,@
  7. 1,1,4320779.030,37455809.964
  8. 2,1,4320619.166,37455886.015
  9. 3,1,4320586.758,37455875.298
  10. 4,1,4320569.917,37455893.435
  11. 5,214.6,LY61082101-37(19),大当镇公草湾林场、臭管站,面,J49G032033、J49G033033,有林地、灌木林地,031、032,,@
  12. 1,1,4283530.626,37417702.335
  13. 2,1,4283527.059,37417698.981
  14. 3,1,4283518.627,37417688.124
  15. 4,1,4283514.847,37417683.714
  16. 5,1,4283510.857,37417678.464
  17. 4,31.6,FK61082101-08(18),塔哈镇石圪台村,面,J49G015035,采矿用地,204,@
  18. 1,1,4364946.560,37426185.842
  19. 2,1,4364946.560,37426196.079
  20. 3,1,4364946.560,37426207.194
  21. 4,1,4364945.976,37426216.846
复制代码
这个文件可以拆分为3个txt(由数字部分可以判断出),每个拆分后的txt共用原始.txt的前5行,拆分后的txt命名为LY61082101-36(19).txt、LY61082101-37(19).txt等
拆分后的txt及原始.txt见附件,这个txt只有三部分,请教下大佬如果多的话如何批处理,谢谢!
附件:https://www.lanzous.com/i3ckfrc
作者: ivor    时间: 2019-3-7 17:56

  1. $file = "C:\Users\mac\Desktop\原始.txt"
  2. $head = gc $file -TotalCount 5
  3. gc $file | select-object -skip 5  | %{
  4. if(($match = [regex]::Match($_,"[A-Z]{2}\d{8}-.{6}")).Length -ne 0){
  5.     $newFile = $match.Value+".txt"
  6.     Set-Content -Value $head -Path $newFile
  7.     Add-Content -Value $_ -Path $newFile
  8. }else{
  9.     Add-Content -Value $_ -Path $newFile
  10. }
  11. }
复制代码

作者: 爱琴海不会走    时间: 2019-3-7 19:25

回复 2# ivor


    大哥,这个杂用啊?不是bat?
作者: ivor    时间: 2019-3-7 19:26

  1. <# :
  2. @echo off
  3. rem 增强代码兼容性,代码保存为 ".bat"、".cmd"、".ps1"均可执行
  4. powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned
  5. more +8 "%~f0" > "%~dpn0.ps1"
  6. powershell -File "%~dpn0.ps1"
  7. del "%~dpn0.ps1"&pause&exit /b
  8. #>
  9. $file = "C:\Users\mac\Desktop\原始.txt"
  10. $head = gc $file -TotalCount 5
  11. gc $file | select-object -skip 5  | %{
  12. if(($match = [regex]::Match($_,"[A-Z]{2}\d{8}-.{6}")).Length -ne 0){
  13.     $newFile = $match.Value+".txt"
  14.     Set-Content -Value $head -Path $newFile
  15.     Add-Content -Value $_ -Path $newFile
  16. }else{
  17.     Add-Content -Value $_ -Path $newFile
  18. }
  19. }
复制代码





欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2