Home > OS >  How to parse command outptut and store in a file
How to parse command outptut and store in a file

Time:01-31

I am executing command and parsing the command based on space, Formatting it and storing in a file.

This is how I have written the batch script

for /f "tokens=2,4,5" %G IN ('command') DO echo Accurev Build Id:%%G:~0,-1%  Timestamp:%H %I > C:\Users\TJainMJ\Documents\out1.txt

I am getting the output like this

Accurev Build Id:3495068:~0,-1;  Timestamp:2023/01/25 14:57:18

But I am trying to trim the ";" semicolon but it's not trimmimg instead it's adding the trim logic to output.

I am expecting output like.

Accurev Build Id:3495068  Timestamp:2023/01/25 14:57:18

Is anything I am missing here.

CodePudding user response:

You cannot substring a metavariable like %%G. You can only substring ordinary variables.

for /f "tokens=2,4,5" %G IN ('command') DO set "buildid=%G"&call echo Accurev Build Id:%buildid:~0,-1%  Timestamp:%H %I> C:\Users\TJainMJ\Documents\out1.txt&set "buildid="

should solve your problem, but it would be much better as a batch file where you don't have to retype the line every time you want to use it.

@ECHO OFF
SETLOCAL
for /f "tokens=2,4,5" %%G IN ('command') DO set "buildid=%%G"&>"u:\q75219686.txt" call echo Accurev Build Id:%%buildid:~0,-1%%  Timestamp:%%H %%I&set "buildid="
TYPE "u:\q75219686.txt"
GOTO :EOF

where "u:\q75219686.txt" is my destination file used for testing

CodePudding user response:

Consecutive delimiters are treated as one. You split by Spaces, if you just add the semicolon to the delimiters, every space, every semicolon and every combination of those will be treated as (one!) delimiter.

for /f "tokens=2,4,5 delims=; " %%G IN ('echo transaction 3495068; promote; 2023/01/25 14:57:16 ; user: thejas') DO echo Accurev Build ID:%%G  Timestamp:%%H 

Output:

Accurev Build ID:3495068  Timestamp:2023/01/25

Note: the space must be the last char in delims=, or you get a syntax error.

  • Related