[英]Powershell Regex replace
Team, 球队,
I have a file in Windows where the content is like the below: 我在Windows中有一个文件,其内容如下所示:
460 ls
460升
461 cd ..
461 CD ..
462 ls
462升
463 cd ubuntu/
463 cd ubuntu /
464 ls
464升
465 cd test/
465 cd测试/
466 ls
466升
467 cd ..
467 CD ..
468 openvpn
第468章
I want to remove all the numbers which are present in the beginning and get the actual content. 我想删除开头出现的所有数字并获取实际内容。
I have tried : 我努力了 :
$var= Get-Content C:\Scripts\test.txt
$var.replace("/[4 6]/","");
$var.replace("/[4 6]/","");
($var.replace("4","")).Replace("6","")
But is it possible to get some regular expression solution for this. 但是有可能为此获得一些正则表达式解决方案。
When processing a file line by line you may use the following pattern: 逐行处理文件时,可以使用以下模式:
$var -replace '^[\s\d]+'
See the regex demo 见正则表达式演示
When processing a whole file as one string you would need to use 将整个文件作为一个字符串处理时,需要使用
$var -replace '(?m)^[\p{Zs}\t\d]+'
in order not to overflow across lines. 为了不跨线溢出。 See a .NET regex demo .
请参阅.NET正则表达式演示 。
Details 细节
^
- start of the input (when (?m)
is used at the start of the pattern, ^
matches start of input and start of each line) ^
-输入的开始(当在模式的开始使用(?m)
时, ^
匹配输入的开始和每行的开始) [\\s\\d]+
- one or more whitespaces ( \\s
) or digits ( \\d
) [\\s\\d]+
-一个或多个空格( \\s
)或数字( \\d
) [\\p{Zs}\\t]
- matches any horizontal whitespace. [\\p{Zs}\\t]
-匹配任何水平空白。 You can do so by using the following regular expression. 您可以通过使用以下正则表达式来实现。
$result = $var -replace '^[\s]?\d+'
To update the file with the $result
you can use the code below. 要使用
$result
更新文件,您可以使用以下代码。
Set-Content -Value $result -Path C:\Scripts\test.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.