如何-仅查找和替换首次出现 [英] How to - Find and replace the first occurrence only

查看:77
本文介绍了如何-仅查找和替换首次出现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个似乎只能正常运行的脚本.我的文件包含多行,字符串为"PROCEDURE DIVISION.",结尾为句点.

I have a script that seems to work correctly only it works to good. I have files that contain multiple lines with the string "PROCEDURE DIVISION.", with the period at the end.

我需要做什么...

仅除去字符串"PROCEDURE DIVISION"的[第二次出现].(如果它在文本文件中两次),并且如果只被发现一次,则绕过文件.我需要保留第一个匹配项并更改/删除第二个匹配项.

ONLY remove the [2nd occurrence] of the string "PROCEDURE DIVISION." if it's in the text file twice and bypass the file if it is only found once. I need to preserve the 1st occurrence and change/remove the 2nd occurrence.

我可以轻松找到并替换所有出现的地方,我不知道如何仅替换2个中的1个.

I can find and replace all the occurrences easily, I have no clue how to replace only 1 of 2.

使用Powershell可以吗?

Is this possible using Powershell?

到目前为止,这是我的代码...

Here is my code so far...

Get-ChildItem 'C:\Temp\*.cbl' -Recurse | ForEach {#
     (Get-Content $_ | ForEach   { $_ -replace "PROCEDURE DIVISION\.", "                   "}) | Set-Content $_ 
} 

更新

我让它工作了,而且不漂亮.

I got this to work and it's not pretty.

唯一的问题是捕获注释部分中的字符串.我需要做的是仅在找到每行第8位的字符串时将其计为命中率.

The only problem is is is capturing the string in the comments section. What I need to do is only count the string as a hit when it's found starting in position 8 on each line.

有可能吗?

Get-ChildItem 'C:\Thrivent\COBOL_For_EvolveWare\COBOL\COBOL\*.*' -Recurse | ForEach {
     ($cnt=(Get-Content $_ | select-string -pattern "PROCEDURE DIVISION").length)
     if ($cnt -gt "1") {
        (Get-Content $_ | ForEach   { $_ -replace "PROCEDURE DIVISION\.", "                   "}) | Set-Content $_
           $FileName = $_.FullName
           Write-Host "$FileName = $cnt" -foregroundcolor green
      } 

推荐答案

所有提供的答案都有潜在的问题.使用 switch 语句读取文件可能是最快的方法.但是它需要考虑 PROCEDURE DIVISION..在同一行上多次出现.与使用 switch 相比,以下方法将占用更多的内存,但将考虑多匹配,单行的情况.请注意,您可以使用 -cmatch 进行区分大小写的匹配.

There are potential issues with all of the provided answers. Reading a file using switch statement is likely going to be the fastest method. But it needs to take into account PROCEDURE DIVISION. appearing multiple times on the same line. The method below will be more memory intensive than using switch but will consider the multi-match, single line condition. Note that you can use -cmatch for case- sensitive matching.

# Matches second occurrence of match when starting in position 7 on a line
Get-ChildItem 'C:\Temp\*.cbl' -Recurse -File | ForEach-Object {
    $text = Get-Content -LiteralPath $_.Fullname -Raw
    if ($text -match '(?sm)(\A.*?^.{6}PROCEDURE DIVISION\..*?^.{6})PROCEDURE DIVISION\.(.*)\Z') {
        Write-Host "Changing file $($_.FullName)"
        $matches.1+$matches.2 | Set-Content $_.FullName
    }
}
    

这篇关于如何-仅查找和替换首次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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