0

i have a *.txt file with several lines as follow

test1
A1 1 2 3 4
b2.13 
C3.14
D63829
A0 B1.1 C1.2 Z1.3
H1 Z0 K2.3 
A0 B1.2 C1.2 Z1.1
A0 B1.3 C1.4 Z1.5
......

i want to have a batch file, to open, read and find line "H1 Z0 K2.3" and insert two new lines like

test1
    A1 1 2 3 4
    b2.13 
    C3.14
    D63829
    A0 B1.1 C1.2 Z1.3
    H1 Z0 K2.3 
    T20
    T19
    A0 B1.2 C1.2 Z1.1
    A0 B1.3 C1.4 Z1.5
    ......

indeed, i wrote the following code, but it doesn't work!any help will be greatly appreciated

@ECHO OFF
::set SrcFolder=c:\test
::set DstFolder=C:\test1

set inputfile=C:\Users\old.txt
set outputfile=C:\Users\new.txt

for %%a in ("%inputFile%") do (
  (for /f "usebackq delims=" %%h in ("%%a") do (
    if "%%h" equ "H1 Z0 K2.3 " (
      echo T20
      echo T19
    ) else (
    echo.%%h
    )
  ))>"%outputfile%\%%~nxa"
)

ECHO.
ECHO Done!
  • To me, this `set outputfile=C:\Users\new.txt` and this `"%outputfile%\%%~nxa"` "seems" not very compatible. What `C:\Users\new.txt` is, a file or a folder? – MC ND Jun 13 '14 at 05:47
  • You forgot to enclose "save" word between quotes in the title! **`;-)`** – Aacini Jun 13 '14 at 06:21

2 Answers2

1
@ECHO OFF
setlocal

::set SrcFolder=c:\test
::set DstFolder=C:\test1

set inputfile=C:\Users\old.txt
set outputfile=C:\Users\new.txt

(for /F "usebackq delims=" %%a in ("%inputFile%") do (
   echo %%a
   if "%%a" equ "H1 Z0 K2.3 " (
      echo T20
      echo T19
   )
)) > "%outputfile%"

ECHO/
ECHO Done!
Aacini
  • 65,180
  • 12
  • 72
  • 108
0

I believe Aacini solved the minor problems with your code, and simplified it.

But I almost never use FOR /F to modify text files any more. I find it to be needlessly complicated and slow. Instead I use REPL.BAT - a hybrid JScript/batch utility that performs a regex search and replace on stdin and writes the result to stdout. It is pure script that runs natively on any modern Windows machine from XP upward. Full documentation is embedded within the script.

Using REPL.BAT with a regular expression:

type old.txt | repl "^H1 Z0 K2\.3 $" "$&\r\nT20\r\nT19" X >new.txt

or with a string literal:

type old.txt | repl "H1 Z0 K2.3 " "H1 Z0 K2.3 \r\nT20\r\nT19" LBEX >new.txt
Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390