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?
1 Answer
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.
2 Comments
Aacini
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!
findorfindstr, and alsofor /F? type the command followed by/?in command prompt for details...\"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 somejsonfile so maybe there are better ways, e.g. parsing and replacing.