gpt4 book ai didi

regex - 如何对powershell中文件中的每一行使用正则表达式

转载 作者:行者123 更新时间:2023-12-01 09:13:30 25 4
gpt4 key购买 nike

在一个文件中我有这样的一行:

I     have lot         of spaces in      me.

我用这个 powershell 代码将每个空格替换为一个空格:

$String = "I     have lot         of spaces in      me."
while ($String.Contains(" "))
{
$String = $String -replace " "," "}

结果是:

我有很多空间。

我想对 txt 文件中的每一行都这样做。你能给我最好的方法吗?


第二部分:

如何仅在有多个空格时替换某些内容,例如;?

响应将是:

;4828;toto;toto;Ticket;0112APPT

而不是:

;4828;toto toto;Ticket;0112APPT

为了清楚起见,我只想用字符 ;

替换两个 White-Space

最佳答案

就像我在评论中说的那样,这应该为你做(至少在我的测试中):

Get-Content yourfile.txt | % {$_ -replace '\s+', ' '}

说明:

Get-Content - 从给定文件中获取内容

| % - Get-Content

给出的每一行内容

$_ -replace '\s+', ' ' - '\s+' 代表一个或多个空格


如果您想用替换后的字符串更改文件的内容,您也可以将其通过管道传输到 Set-Content 并将其保存在另一个文件中:

获取内容 yourfile.txt | % {$_ -replace '\s+', ' '} |设置内容 yourOutputFile.txt

If you want to write to the same file in the pipe, take a look at: Why you dont do it!


鉴于您的第二个问题是忽略正则表达式中的单个空格,如果您想用 ; 替换多个空格,这就是您的方法。

这不会用单个空格替换点:

Get-Content yourfile.txt | % {$_ -replace '\s\s+', ';'}

关于regex - 如何对powershell中文件中的每一行使用正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51652216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com