Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 读取文本文件,检查特定位置的值,并在为true时更改_Powershell - Fatal编程技术网

Powershell 读取文本文件,检查特定位置的值,并在为true时更改

Powershell 读取文本文件,检查特定位置的值,并在为true时更改,powershell,Powershell,我需要遍历多个文本文件,检查每行文本的第7位是否有$value,找到时用*替换。但只有当它处于位置7时。我不想改变它,如果它被发现在其他位置。这就是我所能做到的。任何帮助都将不胜感激 Get-ChildItem 'C:\*.txt' -Recurse | foreach $line in Get-Content $_ { $linePosition1to5 = $line.Substring(0,6) $linePosition7 = $

我需要遍历多个文本文件,检查每行文本的第7位是否有$value,找到时用*替换。但只有当它处于位置7时。我不想改变它,如果它被发现在其他位置。这就是我所能做到的。任何帮助都将不胜感激

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

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

我会用正则表达式来做这个。e、 g

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

$Lines -replace '(?m)(^.{6})\$', '$1*'
要解释正则表达式:

?m表示它是多行的,是必需的,因为我使用了原始get内容,而不是提取数组。数组也可以工作,只需要像您这样的循环

^.{6}行开始加上任意6个字符(捕获组1) $转义美元字符


$1*捕获组1保持原样,将$1替换为*,其他未捕获的内容保持不变。

感谢您的代码和解释。我意识到我忽略了-raw选项,它确实起了作用。把它放回去似乎会在每个文件的末尾添加一行。除非你能想出我不该这么做的理由,否则我会把它漏掉的

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

你能给我们提供一些文本文件的例子吗?-raw会给你一个包含整个内容的字符串。否则,您将得到一个每个成员一行的数组。因此,对于生食,您不需要foreach。如果改为使用数组,则可以去掉多行标志。