user3316048
user3316048

Reputation: 33

Batch script to change txt file

I have a txt file in format:

text1.text2.text3   text4   text5   text6
text7.text8.text9   text10  text11  text12
etc....

I need a script which will make a new txt file wih format:

<record>
<string id="day_of_month" value="text1"/>
<string id="month" value="text2"/>
<string id="year" value="text3"/>
<string id="time" value="tekst4"/>
<string id="home_team_id" value="text5"/>
<string id="away_team_id" value="text6"/>
</record>
<record>
<string id="day_of_month" value="text7"/>
<string id="month" value="text8"/>
<string id="year" value="text9"/>
<string id="time" value="text10"/>
<string id="home_team_id" value="text11"/>
<string id="away_team_id" value="text12"/>
</record>
etc....

etc.... mean that the number of rows isn't defined.

Upvotes: 0

Views: 482

Answers (2)

mbroshi
mbroshi

Reputation: 989

The following script will work:

@echo off

set in=in.txt
set out=output.txt

(for /f "tokens=1-6 delims=. " %%i in (
    %in%
) do (
    echo ^<record^>
    echo ^<string id="day_of_month" value="%%i"/^>
    echo ^<string id="month" value="%%j"/^>
    echo ^<string id="year" value="%%k"/^>
    echo ^<string id="time" value="%%l"/^>
    echo ^<string id="home_team_id" value="%%m"/^>
    echo ^<string id="away_team_id" value="%%n"/^>
    echo ^</record^>
)) > %out%

Upvotes: 1

dbenham
dbenham

Reputation: 130809

The very efficient solution below uses REPL.BAT - a hybrid JScript/batch utility that performs a regular expression search and replace on each line of stdin and writes the result to stdout. The utility is pure native script that will run on any modern Windows machine from XP onward, without any need of 3rd party .exe files. Full documentation is embedded within REPL.BAT.

Assuming REPL.BAT is in your current directory, or better yet, somewhere within you PATH, then:

@echo off
setlocal enableDelayedExpansion

:: Setup search and replace strings
set "search=(.*?)\.(.*?)\.([\S]*)\s*([\S]*)\s*([\S]*)\s*(.*)"
set "repl=<record>\r\n"
set "n=1"
for %%A in (day_of_month month year time home_team_id away_team_id) do (
  set "repl=!repl!<string id=\q%%A\q value=\q$!n!\q/>\r\n"
  set /a n+=1
)
set "repl=!repl!</record>"

:: Do all the work
type input.txt|repl.bat search repl xv >output.txt

Upvotes: 0

Related Questions