在一个文件中我有那种线:
I have lot of spaces in me.
Run Code Online (Sandbox Code Playgroud)
我用这个powershell代码用一个空格替换每个空格:
$String = "I have lot of spaces in me."
while ($String.Contains(" "))
{
$String = $String -replace " "," "}
Run Code Online (Sandbox Code Playgroud)
结果是:
I have lot of spaces in me.
我想对txt文件中的每一行执行此操作.你能给我最好的方法吗?
第二部分:
如果有多个空格,例如,我怎样才能更换东西;?
答复将是:
;4828;toto;toto;Ticket;0112APPT
Run Code Online (Sandbox Code Playgroud)
并不是 :
;4828;toto toto;Ticket;0112APPT
Run Code Online (Sandbox Code Playgroud)
要清楚,我想用角色替换两个白空间 ;
就像我在评论中所说,这应该为你做(至少在我的测试中):
Get-Content yourfile.txt | % {$_ -replace '\s+', ' '}
Run Code Online (Sandbox Code Playgroud)
说明:
Get-Content - 从给定文件中获取内容
| % - 给出的内容的foreach行 Get-Content
$_ -replace '\s+', ' '- '\s+' 代表一个或多个空格
如果要使用替换的字符串更改文件的内容,您还可以Set-Content将其管道并将其保存在另一个文件中:
Get-Content yourfile.txt | % {$_ -replace '\s+', ' '} | Set-Content yourOutputFile.txt
如果要写入管道中的同一文件,请查看:为什么不这样做!
鉴于您的第二个问题是忽略正则表达式中的单个空格,如果您想要用多个空格替换多个空格,那么这就是您要去的方法;.
这不会用一个空格替换斑点:
Get-Content yourfile.txt | % {$_ -replace '\s\s+', ';'}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
399 次 |
| 最近记录: |