[英]How to replace the second occurrence of a character in powershell?
我真的在努力完成一项可能比我想象的更容易的任务。
我有一个包含很多行的文件:
例如
"numbers TG alongstring"
"numbers 100 alongstring"
"numbers 120 alongstring"
"numbers AF alongstring"
"numbers 123 alongstring"
我想替换第二次出现
(空格)与
(两个空格)使长字符串彼此对齐。 2 个字符长的字符串始终是数字。
像这样的东西:
"numbers TG alongstring"
"numbers 100 alongstring"
"numbers 120 alongstring"
"numbers AF alongstring"
"numbers 123 alongstring"
需要注意的是,开头的数字在 4000 行中是唯一的,并且长字符串的长度也不相同。
到目前为止我所拥有的:
foreach ($Line in $file) {
if ($Line[10] -eq " ") {
$Line.Replace(" ", " ")
}
}
[10] 是我要替换的空间的索引。
这用双空格替换了所有单空格我尝试了很多东西,但到目前为止还没有任何运气。
任何帮助是极大的赞赏。
将(?m)(^[^\n\r ]* [^\n\r ]{2})
(它包含一个尾随空格)替换$1
(它包含一个双尾随空格)。
仅当前面有两个非空格字符时,此正则表达式才会用双空格替换第二个单空格出现。
(?m)
是多行标志^
匹配行的开头(因为(?m)
,否则它会匹配字符串的开头)[^\n\r ]*
匹配零个或多个既不是空格也不是换行符的字符[^\n\r ]{2}
恰好匹配两个既不是空格也不是换行符的字符(...)
是一个捕获组,你用$1
引用它在此处查看演示。
尝试测试.LastIndexOf( ' ' )
返回。 如果空间的最后一个索引是 10,你就知道你缺少一个空间。 然后可以使用.Insert()
方法将其添加到同一个 position 中。
也许是这样的:
foreach ($Line in $file) {
if ($Line.LastindexOf( ' ' ) -eq 10 ) {
$Line.Insert( 10, ' ' )
}
}
像这样的东西可以工作,你应该能够为匹配标准提出一个通用模式。
Get-Content $file | Foreach-Object {
# matches <nonspaces><space><nonspaces><spaces><rest of string>
if ($_ -match '^([^ ]+ \S+ +)(.*)$') {
# $matches.1 is everything matching in the first ()
# $matches.2 is everything matching in the second ()
# Assumes alongstring desirably lines up at position 13 starting from 0. Change 13 to the appropriate number if necessary
($matches.1).PadRight(13,' ') + $matches.2
} else {
$_
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.