0

I have a text file "info.txt" that contains various strings. I want to find the first occurrence of the string '"masterstring":' and replace everything after '"masterstring":' with "replacement data text" but only up until the next comma , What is the fastest way to do this with a .bat script?

4
  • My first response would be look at perl. you can write a regex te replace certain text and is fast Commented Dec 4, 2015 at 11:34
  • What have you tried so far? do you know the commands find or findstr, and also for /F? type the command followed by /? in command prompt for details... Commented Dec 4, 2015 at 11:43
  • Generally, you could come up with sth. like \"masterstring\":([^,]*)that is, match "masterstring" and a colon literally, then capture everything up to a comma in a group. See this regex101 fiddle for a working demo. However, this looks like to be some json file so maybe there are better ways, e.g. parsing and replacing. Commented Dec 4, 2015 at 12:47
  • thanks for your help guys. unfortunately i can only do this with a bat or vbs file in this situation. any ideas? Commented Dec 4, 2015 at 12:53

1 Answer 1

1

You may write a .VBS script to do this, but it is easier to use JScript instead, because both Batch and JScript code can be combined in the same hybrid file with .BAT extension. I copied the solution at this post and slightly modified it for this request.

@set @a=0  /*
@cscript //nologo //E:JScript "%~F0" < input.txt > output.txt
@goto :EOF */

WScript.Stdout.Write(WScript.StdIn.ReadAll().replace(/masterstring.*,/,"masterstring replacement data text,"));

You have not posted a sample data, so I created a simple input file:

First line in data file.
First line with masterstring and data to be replaced, preserve text after comma.
Other line with masterstring and other data, that must not be changed.
Last line in file.

This is the output:

First line in data file.
First line with masterstring replacement data text, preserve text after comma.
Other line with masterstring and other data, that must not be changed.
Last line in file.

For further details on this method, see the link above and the links at that post. You may also search for "jscript replace" and for "jscript hybrid" with batch-file tag in this site.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. This is on the right path but i'm having some issues. How do i find the following, with quotes included: "masterstring":"
You should use code tags to clearly delimit your examples. Is it "masterstring":" or "masterstring": ? Any other? Please, post a short example of an input and the desired output based on such input; otherwise this just becomes a guessing game... Edit your question (do NOT post data in comments) and use code tags!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.