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?

  • My first response would be look at perl. you can write a regex te replace certain text and is fast – lordkain Dec 04 '15 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... – aschipfl Dec 04 '15 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](https://regex101.com/r/rF4aV3/1) for a working demo. However, this looks like to be some `json` file so maybe there are better ways, e.g. parsing and replacing. – Jan Dec 04 '15 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? –  Dec 04 '15 at 12:53

1 Answers1

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.

Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
  • Thanks. This is on the right path but i'm having some issues. How do i find the following, with quotes included: "masterstring":" –  Dec 05 '15 at 08:22
  • 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! – Aacini Dec 05 '15 at 20:06