JREPL - How to replace only the second match in a text file?

71 Views Asked by At

Is it possible to tell "JREPL.bat" to only replace the second match of "[AddReg]" in a text file? I have tried to find a solution for days now, but failed.

The "JREPL.bat" command /INC "3:7" does not help because the line numbers will change too much depending on the text file.

CALL ".\JREPL.bat" "\[AddReg\]" "[AddReg]\r\nNewLine." /XSEQ /M /F "test.txt" /O "test1.txt"

[AddReg]
1TEST.
2TEST.
3TEST.
[AddReg]
1TEST.
2TEST.
3TEST.
[AddReg]
1TEST.
2TEST.
3TEST.
2

There are 2 best solutions below

0
Aaron Meese On

As far as I can tell, there is no native way to accomplish this with JREPL.bat. However, if you're willing to use a custom Batch script to accomplish this, something along the lines of the following will do:

@echo off
setlocal enabledelayedexpansion

set "input_file=test.txt"
set "output_file=test1.txt"
set "search_string=[AddReg]"
set "replace_string=[AddReg]\r\nNewLine."

set "count=0"

(for /f "tokens=*" %%a in (%input_file%) do (
    set "line=%%a"
    if !count! lss 2 (
        set "line=!line:%search_string%=%replace_string%!"
        if not "!line!"=="%%a" (
            set /a "count+=1"
        )
    )
    echo !line!
)) > %output_file%

endlocal

The script will ignore the first match, replace the second, then exit the loop.

0
Mike0101 On

Natively "JREPL.bat" doesn't support this, which is strange. But I found one solution for this problem. Any more ideas are welcome.

CALL ".\JREPL.bat" "\[AddReg\]" "$txt=++counter==2?'[AddReg]\r\nMy Little Pony':$0" /JQ /F "test.txt" /O "test1.txt"