Computing.Net > Forums > Programming > batch file to reformat text file

batch file to reformat text file

Reply to Message Icon

Original Message
Name: fastermech
Date: May 14, 2007 at 09:14:45 Pacific
Subject: batch file to reformat text file
OS: XP Pro 2002 SP2
CPU/Ram: 1.8GHz/1GB
Model/Manufacturer: IBM/T42
Comment:

I have a file that I need to reformat via either a batch file or VB Script. original sample line of text

"20070301000231","501",65385,21.472,"0008"
"20070510103100","523",65221,19.667,"0002"


I need the new format to be

"20070301 000231","501",65385,21.472,"0008"
"20070510 103100","523",65221,19.667,"0002"

can a non-delimited field be parsed in a batch file?
thanks...ralph


Report Offensive Message For Removal


Response Number 1
Name: FishMonger
Date: May 14, 2007 at 11:05:13 Pacific
Reply: (edit)

Between your 2 choices of scripting languages, VB would be best.

I don't work with VB, but here's a Perl commamd line regex solution that can be translated to the VB equivalent.

===================================
perl -pe "s/^(\"\d{8})(\d{6}\")/$1 $2/" file.txt



Report Offensive Follow Up For Removal

Response Number 2
Name: ghostdog
Date: May 14, 2007 at 17:10:46 Pacific
Reply: (edit)

I don't know VB much, here's one in Python
[code]
for line in open("file"):
line = line.split(",")
print line[0][0:9],line[0][9:]+",",','.join(line[1:])
[/code]
save as script.py and from commandline,
c:\> python script.py > outfile

however if you also have GNU awk,
[code]
awk 'BEGIN{FS=","}{$1=substr($1,0,9)" "substr($1,9);$0=$0;print} ' file
[/code]


Report Offensive Follow Up For Removal

Response Number 3
Name: Shr0Om
Date: May 15, 2007 at 02:16:07 Pacific
Reply: (edit)

Here's a batch:


@echo off
for /f %%i in (myfile.txt) do (
set line=%%i
call :parser)
goto :eof

:parser
set parsed1=%line:~0,9%
set parsed2=%line:~9,33%
echo %parsed1% %parsed2% >>newfile.txt


Report Offensive Follow Up For Removal

Response Number 4
Name: Razor2.3
Date: May 16, 2007 at 20:04:41 Pacific
Reply: (edit)

For the sake of completeness, the VBScript code:

Dim fso, inF, outF, sLine
Set fso = CreateObject("Scripting.FileSystemObject")
Set inF = fso.OpenTextFile("myfile.txt", 1)
Set outF = fso.OpenTextFile("outfile.txt", 2, True)

Do Until inF.AtEndOfStream
sLine = inF.ReadLine
outF.WriteLine Left(sLine, 9) & " " _
& Right(sLine, Len(sLine) - 9)
Loop



Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: batch file to reformat text file

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 5 Days.
Discuss in The Lounge