Sandra
Sandra

Reputation: 13

Batch modifying text.txt before a specific word

I have a file.txt where there are lines as

IF TANK T395 LEVEL ABOVE 4 THEN PUMP PFALDA395&T395 STATUS IS CLOSED 

that I would like to transform in

IF TANK T395 LEVEL ABOVE 4
THEN PUMP PFALDA395&T395 STATUS IS CLOSED                                 

I tried with this code.bat

@echo off
del "newfile.txt" 2>nul
(
    for /f "eol=| usebackq for /f tokens=1,2,3,4,5,6,* delims= " %%a %%b %%c %%d %%e %%f %%g in ("oldfile.txt") do (
        for /f  %%h in ("%%g") do ( 
            if /i "%%h"=="THEN" ( 
                echo %%a %%b %%c %%d %%e %%f
                echo. %%g
            )
        )
        echo %%a %%b %%c %%d %%e %%f %%g
    )
)>"newfile.txt"

I got a fast

%b non atteso (not waited)

What am I stumbling in?

Upvotes: 0

Views: 69

Answers (2)

aschipfl
aschipfl

Reputation: 34909

You tried to specify variables for all tokens in the outer for command, but you must specify only the first one, which is %%a in your case; all the others (%%b, %%c,..., %%g) are defined implicitly via the tokens option (see also @Stephan's comment).

Besides that, your code outputs the original and the split line into the output file. Hence I inserted an else clause.

Finally, I implemented an additional condition: the code searches for IF as well now and splits therefore only lines which start with IF and contain THEN as the 7th token.

@echo off
del "newfile.txt" 2> nul
(
    for /f "eol=| usebackq tokens=1,2,3,4,5,6,* delims= " %%a in ("oldfile.txt") do (
        if /i "%%a"=="IF" (
            for /f "eol=| tokens=1 delims= " %%h in ("%%g") do ( 
                if /i "%%h"=="THEN" ( 
                    echo %%a %%b %%c %%d %%e %%f
                    echo %%g
                ) else (
                    echo %%a %%b %%c %%d %%e %%f %%g
                )
            )
        ) else (
            echo %%a %%b %%c %%d %%e %%f %%g
        )
    )
) > "newfile.txt"

Edit:
The above solution can be simplified after following @Aacini's comment:

@echo off
del "newfile.txt" 2> nul
(
    for /f "eol=| usebackq tokens=1-7* delims= " %%a in ("oldfile.txt") do (
        if /i "%%a|%%g"=="IF|THEN" (
            echo.%%a %%b %%c %%d %%e %%f
            echo.%%g %%h
        ) else (
            echo.%%a %%b %%c %%d %%e %%f %%g %%h
        )
    )
) > "newfile.txt"

Herein, only one for loop and one if clause is required.

Upvotes: 0

Stephan
Stephan

Reputation: 56180

just replace every <space>THEN<space> with <newline>THEN<space>:

@echo off
setlocal enabledelayedexpansion

REM Creating a Newline variable (the two blank lines are required!)
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%

for /f "delims=" %%a in (t.txt) do (
  set line=%%a
  echo(!line: THEN =%NL%THEN !
)

(I took the creation of a NewLine from here)

Upvotes: 2

Related Questions