读取文本文件并检查特定位置的值并在为真时更改 [英] Read text file and check for value in a specific position and change when true

查看:32
本文介绍了读取文本文件并检查特定位置的值并在为真时更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历多个文本文件并检查每行文本中位置 7 处的 $ 值,并在找到时将其替换为 *.但仅当它在位置 7 时.如果在其他位置找到它,我不想更改它.这是我得到的.任何帮助将不胜感激.

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 $_
        }

推荐答案

在您的示例中是否有某些东西不起作用,或者只是所有嵌套的子字符串在使用时都很烦人?

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*'

解释正则表达式:

?m 表示它是多行的,因为我使用原始 get-content 而不是拉数组.数组也可以,只需要像你一样的循环.

?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} 行开始加上任意 6 个字符(捕获组 1)$ 转义美元字符

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

$1* 捕获组 1 保持原样,美元替换为 *,其他任何未捕获因此保持不变.

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

这篇关于读取文本文件并检查特定位置的值并在为真时更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆