2

i run a command(mycommand) in windows which returns a json file on that i do the following operation

<mycommand> | findstr /r InstanceId >instance.txt

which returns "InstanceId": "i-59df8e93", as output. now what i wish to do is i just want the part that will always be after the InstanceId: and before the ,.

How to do that in windows command prompt ?

EDIT 1: i have made progress till here,

content of Instance1.txt :

   "InstanceId": "i-59df8e93"

I used the following command :

FOR /F "tokens=1,2,3 delims=:" %G IN (instance1.txt)  DO @echo %G %I> instance1.txt

it returns "InstanceId"

i wanted these two tokens to in different variables. so that i can extract i-59df8e93. How to proceed ?

Subham Tripathi
  • 2,683
  • 6
  • 41
  • 70

1 Answers1

3

Reference for /f

Source file:

"InstanceId": "i-59df8e93"

You need to use " as a delimeter and extract the 3rd token.

The easiest wasy to use " as a delimeter is by using the following 'trick' (reference answer to Escaping double-quote in delims option of for /F by rkagerer):

  1. use ^ (as long as it is not present in the file) as the delimeter
  2. swap the order of delims and tokens

Now you can use the following command to extract i-59df8e93:

for /f delims^=^"^ tokens^=3 %a in (instance.txt) do @echo %a

Output:

i-59df8e93

Note: I've used instance.txt as this file was the output of the original command.

To add this value to instance1.txt:

for /f delims^=^"^ tokens^=3 %a in (instance.txt) do @echo %a > instance1.txt

Putting it all together in a batch file:

<mycommand> | findstr /r InstanceId >instance.txt
for /f delims^=^"^ tokens^=3 %%a in (instance.txt) do @%echo %%a > instance1.txt

Note: In a batch file you need to replace % with %%.

Community
  • 1
  • 1
DavidPostill
  • 7,734
  • 9
  • 41
  • 60