mez
mez

Reputation: 13

Processing pipe symbol in command output

I have problem to process command output which contains pipeline symbol |.

Running command

wget.exe -O- -q http://192.168.1.200/get_sys[310]?rn=2  

outputs (for example)

2512|2250  

but using it in batch

for /f "delims=" %%a in ('wget.exe -O- -q http://192.168.1.200/get_sys[310]?rn=2') do set tep=%%a
echo %tep%  

gets output stuck. I have to use ^C (and answer No to question if to break batch) to continue with echo, then the output is

C:\Batch>set tep=2512
C:\Batch>echo 2512
2512  

instead

2512|2250  

(I need to replace | with other delimiter in fact, but this is not heart of the matter).

I suppose there is problem in this very command output containing pipeline symbol, but I don't know how it works in the concrete and how to solve it.

Note. I can't change the format of command output ever.

Thanks for any suggestions.

Upvotes: 1

Views: 695

Answers (3)

jeb
jeb

Reputation: 82317

The best way of outputting special characters is to use delayed expansion, as then all characters can be handled without problems.
You don't need quotes nor replace/escapes.

for /f "delims=" %%a in ('wget.exe -O- -q http://192.168.1.200/get_sys[310]?rn=2') do ( 
  set "tep=%%a"
)
setlocal EnableDelayedExpansion
echo !tep!
endlocal

Upvotes: 1

MC ND
MC ND

Reputation: 70933

If you run the following cmd file

@echo off

    rem run a command which return a string with a pipe in it
    for /F "tokens=*" %%f in ('type "%~dpnx0" ^| find "DATA:"') do set line=%%f

    rem output the string to the console.
    rem quotes needed so cmd does not interpret pipe character
    echo "%line%"
    exit /b 

    DATA: THIS LINE WILL BE | PROCESSED BY THIS FILE

    rem end of file 

You will see that for command is not failing because of pipe character. It can handle it

When cmd reaches the echo line, it replaces variable reference with variable contents before executing the line. Once replacement is done, the line contains an echo command which pipes to another command. In this sample, to avoid it, i just enclosed the variable in quotes to avoid the pipe character to be considered.

If you need to use the variable as is (no quotes), then pipe character needs to be scaped as

echo %tep:|=^|%

That is, echo the %tep% string with the pipe character replaced with it scaped (the ^)

Why your code gets stuck? It seems more a problem with wget than for command.

Upvotes: 1

npocmaka
npocmaka

Reputation: 57262

Could you try with :

for /f "delims=" %%a in ('wget.exe -O- -q http://192.168.1.200/get_sys[310]?rn=2') do ( 
  set "tep=%%a"
)
echo %tep:|=^|%

this will escape the |

Upvotes: 1

Related Questions