Read text file and check for value in a specific position and change when true

五迷三道 提交于 2021-02-17 06:16:05

问题


I need to loop through multiple text files and check for a $ value in position 7 on each line of text and replace it with an * when found. But ONLY when it is in position 7. I do not want to change it if it is found in other positions. This is as far as I have gotten. Any help would be greatly appreciated.

Get-ChildItem 'C:\*.txt' -Recurse | 
        foreach $line in Get-Content $_  {
        $linePosition1to5 = $line.Substring(0,6)
        $linePosition7    = $line.Substring(6,1)  
        $linePositionRest = $line.Substring(8)  
        if($linePosition7 = "$"){
           $linePosition7 = "*"  
            }
        $linePosition1to5 +  $linePosition7 + $linePositionRest |
     Set-Content $_
        }

回答1:


Is there something that doesn't work in your example, or just that all the nested substrings are annoying to work with?

I'd use regex for this one. e.g.

$Lines = Get-Content -Path "C:\examplefile.txt" -raw

$Lines -replace '(?m)(^.{6})\$', '$1*'

To explain the regex:

?m indicates that it's multiline, required because I used raw get-content rather than pulling an array. Array would work too, just needs a loop like you did.

^.{6} line start plus any 6 characters (capture group 1) $ escaped dollar character

$1* Capture group 1 left as is, dollar replaced with *, anything else not captured and therefore left untouched.




回答2:


Thanks for code and the explanation. I realized that I left out the -raw option and it did work. Putting it back in it seems to add a line to the end of each file. Unless you can think of reason why I shouldn't I was going to leave it out.

Get-ChildItem 'C:\TEST\*.txt' -Recurse | ForEach {
     (Get-Content $_ | ForEach   { $_ -replace '(?m)(^.{6})\$', '$1*'}) |
     Set-Content $_
}


来源:https://stackoverflow.com/questions/64081433/read-text-file-and-check-for-value-in-a-specific-position-and-change-when-true

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!