Remove or comment out string from second occurrence in a file

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
goodywp
Posts: 250
Joined: 31 Jul 2017 09:57

Remove or comment out string from second occurrence in a file

#1 Post by goodywp » 26 Aug 2019 10:16

I have searched and seems not getting a solution.
Here is my task.
I have a catalog file (text file). In this catalog file, I have some contents like this

; Group 1
-epackage
......

;Group 2
-epackage
.....

;Group 1
-eimport
...
;Group 2
-eimport

This above catalog file needed to be remove or replace the second occurrence of string -epackage, -eimport
Since remove string usually leave a blank line. SO probably replace string is a good solution.
So basically replace -epackage from second occurrence to be ;epackage (comment out)
So basically replace -eimport from second occurrence to be ;import (comment out)

Now the desired output from the above catalog file after a batch file processing looks like this

; Group 1
-epackage
......

;Group 2
;-epackage
.....

;Group 1
-eimport
...
;Group 2
;-eimport

this simple piece of code can replace string with all occurrence, how can we keep the first occurrence without replacement...

Code: Select all

type Load_all.txt | powershell -Command "$input | ForEach-Object { $_ -replace \"-epackage\", \";-epackage\" }"> Load_all_new.txt
This simple batch script can delete string without leaving blank line, but it will delete all the occurrence of that string, how to keep the first occurrence

Code: Select all

type Load_all.txt | findstr /v -epackage >>Load_all_new.txt

Post Reply