簡體   English   中英

如何替換 powershell 中第二次出現的字符?

[英]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引用它

在此處查看演示。

在您可以使用的其他解決方案中

^((?:[^\n ]* (?! )){2})

並將其替換為$1
請參閱regex101.com 上的演示

嘗試測試.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM