Board logo

标题: [问题求助] [已解决]求修改PowerShell正则表达式 [打印本页]

作者: smss    时间: 2024-6-19 19:18     标题: [已解决]求修改PowerShell正则表达式

本帖最后由 smss 于 2024-6-21 11:20 编辑

多一行 换行符不一致 明明结尾啥也没有
用Notepad2.exe打开看行尾多出一行CRLF很是奇怪
  1. param([string]$file); #修改前的文件
  2. $file1 = [io.fileinfo]$file;
  3. $file2 = [io.path]::Combine($file1.DirectoryName, $file1.BaseName) + '_整理.h';# 新的路径
  4. -replace'(\[[^]]*\])|(?<=[|!]) +','$1' 会把"-delims:| "或"-delims:, "或"-delims:[ "替换为"-delims:|"或"-delims:,"或"-delims:["
  5. #修改以下PowerShell 当其中出现"-delims:| "或"-delims:, "或"-delims:[ "  等只要-delims: 出现则不替换
  6. #例如
  7. MSTR * -delims:,&i,&j=<1*>&k 则替换变为 MSTR * -delims:, &i,&j=<1*>&k
  8. MSTR * -delims:, &i,&j=<1*>&k 则不替换不做任务操作
  9. MSTR * -delims:%a% &i,&j=<1*>&k 则不替换不做任务操作
  10. #我尝试
  11. -replace'(\[[^]]*\])|(?<=[|!])(?<!-delims:) +','$1'
  12. -replace'delims:(\[|,|\|)','delims:$1 '
  13. -replace 'delims:(.)(?=\S)(?!:)','delims:$1 ' 但遇MSTR * -delims:%a% 又会被分割成 -delims:% a%
  14. (Get-Content $file2) | ForEach-Object {
  15.     if ($_ -notmatch "-delims:\s*\S") {
  16.         $_ -replace "-delims:", "-delims: "
  17.     } else {
  18.         $_
  19.     }
  20. } | Set-Content $file2
  21. (Get-Content $file -ReadCount 0)-replace'(\[[^]]*\])|(?<=[|!]) +','$1'-replace'ENVI ','set '-replace'ENVI\^','set^'-replace'envi$','set$'-replace'envi~','set~'-replace'envi\.','set.'-replace'envi<','set<'-replace'envi-ret','set-ret'|Set-Content -encoding Unicode $file2
  22. #替换后行尾多出一行CRLF
  23. (Get-Content -Raw -Path $file2 -Encoding Unicode) -replace "`r`n", "`n"| Set-Content -Path $file2 -Encoding Unicode
复制代码
用以下脚本解决
  1. [IO.File]::WriteAllText($file2,([IO.File]::ReadAllText($file, [Text.Encoding]::Unicode) -replace 'ENVI(\^|\$|~|\.|\<|-ret| )','set$1'-replace'\r\n',"`n"),(New-Object System.Text.UnicodeEncoding $fale));
复制代码

作者: newswan    时间: 2024-6-19 21:47

-Raw 的原因,最后一个空行
作者: smss    时间: 2024-6-19 21:51

回复 2# newswan 不加替换不了
作者: Five66    时间: 2024-6-19 22:22

set-content 问题 , 加上 -NoNewline 选项
或者直接用 .net 方法
作者: smss    时间: 2024-6-19 22:43

回复 4# Five66
用Notepad2.exe打开看是没有把换行符CR+LF替换成LF
作者: Five66    时间: 2024-6-19 23:41

回复 5# smss


    说不定是notepad2打开时又自动转成cr lf 了, 试试多换几个编辑器打开对比看看
作者: smss    时间: 2024-6-20 08:25

回复 6# Five66
notepad2不会自动转换的
作者: Five66    时间: 2024-6-20 22:20

回复 7# smss


    额 , 4楼里不是说了 , 该不会加了个选项就出问题吧






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