AllenHu
AllenHu

Reputation: 13

How to echo txt file line by line to specific format with batch?

I have a txt file like this:

3FPC1   00:12:34:56:78:90   192.168.6.1
3FPC2   00:12:34:56:78:91   192.168.6.2

I know how to read txt file line by line by using the following script

@echo off
for /F "tokens=*" %%A in (macip.txt) do echo %%A
pause

But I want to covert content to specific format like:

host 3FPC1 {  
  hardware ethernet 00:12:34:56:78:90;
  fixed-address 192.168.6.1;
}
host 3FPC2 {
  hardware ethernet 00:12:34:56:78:91;
  fixed-address 192.168.6.2;
}

How can I do it?

Is it possible to merge all the echo results and output to a txt file?

Upvotes: 0

Views: 68

Answers (3)

Aacini
Aacini

Reputation: 67216

This is another, perhaps simpler method:

@echo off
(for /F "tokens=*" %%A in (macip.txt) do call :convert %%A) > yes.txt
goto :EOF

:convert
echo host %1 {
echo   hardware ethernet %2
echo   fixed-address %3
echo }

Upvotes: 0

AllenHu
AllenHu

Reputation: 13

Below is my modification and it can works.

@echo off
set filepath=C:\Users\School\Desktop\dhcp\conf
for /f "tokens=1-3 delims=  " %%i in (%filepath%\macip.txt) do (
echo host %%i { > ok%%i.txt
echo. hardware ethernet %%j >> ok%%i.txt
echo. fixed-address=%%k >>ok%%i.txt
echo. } >>ok%%i.txt
echo. >>ok%%i.txt
)
copy *.txt %filepath%\yes.txt
del *.txt
pause

Upvotes: 1

PA.
PA.

Reputation: 29339

You are almost there, tell FOR to parse the line just read.

Read HELP FOR and, instead of "tokens=*", use "tokens=1,2,*" for example

So you can

for /F "tokens=1,2,*" %%A in (macip.txt) do (
  echo host %%A {
  echo.   hardware ethernet %%B;
  echo.   fixed-address %%C;
  echo }
)

Upvotes: 1

Related Questions