找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 14016|回复: 5

[问题求助] [已解决]用powershell正则在特定行后追加多行

[复制链接]
发表于 2023-5-2 22:04:05 | 显示全部楼层 |阅读模式
本帖最后由 小白龙 于 2023-5-3 10:22 编辑

我想在最后一个using开头的行后追加两行文本, 下面的代码没有效果, 求路过大佬指正
原文本:

using System.forms;
using System;

public class cla
{
        public string hello()
        {
                return "hello";
        }
}
最后需要的结果
using System.forms;
using System;
using System.IO;
using System.Text;


public class cla
{
        public string hello()
        {
                return "hello";
        }
}
  1. $content = @'
  2. using System.forms;
  3. using System;

  4. public class cla
  5. {
  6.         public string hello()
  7.         {
  8.                 return "hello";
  9.         }
  10. }
  11. '@
  12. $pattern = '(using\s+.+;)(?=(?:[^{}]*{[^{}]*})*[^{}]*$)'
  13. $replacement = '$&' + "`r`nusing System.IO;" + "`r`nusing System.Text;"
  14. $result = [regex]::Replace($content, $pattern, $replacement)
  15. $filePath = "$HOME\Desktop\a.txt"
  16. Set-Content -Path $filePath -Value $result
复制代码

评分

参与人数 1PB +2 收起 理由
Batcher + 2 感谢给帖子标题标注[已解决]字样

查看全部评分

发表于 2023-5-2 22:32:16 | 显示全部楼层
虽然看不懂ps代码 但是如果是我 我会先定位到最后一个using的行数 在把文本分割成一行一行的数组 再拼接 插入(我这肯定不是最好的办法)
发表于 2023-5-3 08:26:39 | 显示全部楼层
  1. $content = @'
  2. using System.forms;
  3. using System;

  4. public class cla
  5. {
  6.         public string hello()
  7.         {
  8.                 return "hello";
  9.         }
  10. }
  11. '@

  12. $append = @'
  13. using System.IO;
  14. using System.Text;
  15. '@

  16. $result = $content -replace '^(.|\r|\n)*\n\s*using\s+\w+.*?\n', ('$0' + $append + "`n")
  17. $filePath = "$HOME\Desktop\a.txt"
  18. Set-Content -Path $filePath -Value $result
复制代码

评分

参与人数 1技术 +1 收起 理由
小白龙 + 1 乐于助人

查看全部评分

发表于 2023-5-3 09:08:15 | 显示全部楼层
直接$append+$content呗
没必要非要加在后面吧,$append后面加个换行就行
 楼主| 发表于 2023-5-3 10:23:29 | 显示全部楼层
回复 4# pd1


    多谢关注, 主要是想研究一下正则
发表于 2023-5-3 14:16:50 | 显示全部楼层
本帖最后由 newswan 于 2023-5-3 14:32 编辑

  1. $content -replace "(?<=using.*`n)(?=`n)","$append`n"
复制代码
你的示例是 字符串, 如果是字符串数组,又不一样了.
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-17 03:10 , Processed in 0.019083 second(s), 9 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表