user123
user123

Reputation: 425

windows batch file / get last word in a line

I have a weird case in batch file.

I have a txt file named state.txt containing the following line :

State          ON

I need to read the "ON" word (it can be OFF as well), so I'm using the following simple batch file :

@echo off
for /f "tokens=2" %%a in (state.txt) do set word1=%%a
echo %word1%

when executing the batch file , I dont get any output , but when I change the "ON" or "OFF" word to any other word it's shown.

I'm confused here! what's the relation between ON/OFF and the output got.

Upvotes: 2

Views: 661

Answers (1)

zb226
zb226

Reputation: 10500

This is because ON and OFF are special inputs for ECHO which turn command-echoing on or off. Consider this:

SET VAR1=OFF
ECHO %VAR1%
SET VAR2=ON
ECHO %VAR2%
SET VAR3=TEST
ECHO %VAR3%

This will output:

C:\Windows>SET VAR1=OFF
C:\Windows>ECHO OFF
C:\Windows>SET VAR3=TEST
C:\Windows>ECHO TEST
TEST

You're not seeing the VAR2-part, because command-echoing is turned of with VAR1. Your seeing the VAR3-part, since VAR2 turns it on again.

If you want to echo the words ON and OFF, you can do by placing a dot between ECHO and ON or OFF:

C:\Windows>SET VAR4=ON
C:\Windows>ECHO.ON
ON
C:\Windows>SET VAR5=OFF
C:\Windows>ECHO.OFF
OFF

Upvotes: 2

Related Questions