Powershell Regex取代

问题描述 投票:1回答:2

球队,

我在Windows中有一个文件,其内容如下所示:

460 ls

461 cd ..

462 ls

463 cd ubuntu /

464 ls

465 cd测试/

466 ls

467 cd ..

468 openvpn

我想删除开头存在的所有数字并获取实际内容。

我试过了 :

$var= Get-Content C:\Scripts\test.txt
$var.replace("/[4 6]/","");

$var.replace("/[4 6]/","");

($var.replace("4","")).Replace("6","")

但是有可能为此获得一些正则表达式解决方案。

regex powershell
2个回答
5
投票

逐行处理文件时,您可以使用以下模式:

$var -replace '^[\s\d]+'

regex demo

将整个文件作为一个字符串处理时,您需要使用

$var -replace '(?m)^[\p{Zs}\t\d]+'

为了不溢出线。看到.NET regex demo

细节

  • ^ - 输入的开始(当在模式的开头使用(?m)时,^匹配输入的开始和每行的开始)
  • [\s\d]+ - 一个或多个空格(\s)或数字(\d
  • [\p{Zs}\t] - 匹配任何水平空格。

enter image description here


1
投票

您可以使用以下正则表达式执行此操作。

$result = $var -replace '^[\s]?\d+'

要使用$result更新文件,您可以使用以下代码。

Set-Content -Value $result -Path C:\Scripts\test.txt
© www.soinside.com 2019 - 2024. All rights reserved.