Page 1 of 1 1
Topic Options
#207785 - 2013-09-19 10:14 AM Text file manipulation
GeorgeLittle Offline
Fresh Scripter

Registered: 2011-02-08
Posts: 47
Loc: UK
Hi Guys

I have a text file that I need to manipulate on a regular basis to make all rows the same length

eg

Mr A B Sample Test Test NEWField
Mr B B Sample Test Test

So rather than having the CRLF after the second test in Mr B B Sample Id like it to pad it with spaces so each row is of the same length ?

Thanks

Top
#207786 - 2013-09-19 01:06 PM Re: Text file manipulation [Re: GeorgeLittle]
Glenn Barnas Administrator Offline
KiX Supporter
*****

Registered: 2003-01-28
Posts: 4403
Loc: New Jersey
George,

Use my FileIO UDF to make this easy - it loads a file into an array and then writes the array back to the file. Download the latest from the Kix UDF Library on my web site (under IT Resources)
 Code:
Call 'path\fileio.kxf'

$File = 'path\filename.txt'           ; specify your source file

$aFileData = FileIO($File, 'R')       ; load the UDF from the correct path, or copy/paste it here instead

; enumerate the data to find the longest line - unnecessary if you want all at a known fixed length
$Longest = 0
For $R = 0 to UBound($aFileData)
  $L = Len($aFileData[$R]
  If $L > $Longest $Longest = $L EndIf
Next

; Create a "pad string"
$Pad = ''
For $R = 1 to $Longest
  $Pad = $Pad + ' '
Next

; Pad the array values to the desired length
For $R = 0 to UBound($aFileData)
  $aFileData[$R] = Left($aFileData + $Pad, $Longest)
Next

; Write the file data back
$aFileData = FileIO($File, 'W', $aFileData)

; done
Exit 0
Give it a test.. Clean this up with variable declarations and error checking after the FileIO calls before putting it into production.

If you know how long the lines should be, you can eliminate the first For/Next and simply set $Longest = 70 for 70 character lines. This could trim real data if you aren't careful.

If you need to do further data manipulation, it would be done in the third For/Next loop, before the padding statement. Simply break apart and reassemble the $aFileData[x] value. Be sure to read the UDF header as there are some potentially useful options available on write that you may want to take advantage of, including blank line suppression.

Glenn
_________________________
Actually I am a Rocket Scientist! \:D

Top
Page 1 of 1 1


Moderator:  Jochen, Allen, Radimus, Glenn Barnas, ShaneEP, Ruud van Velsen, Arend_, Mart 
Hop to:
Shout Box

Who's Online
1 registered (Henriques) and 2516 anonymous users online.
Newest Members
fgarcia, Viginette, ManuvdWielNL, Sir_Barrington, batdk82
17889 Registered Users

Generated in 0.05 seconds in which 0.025 seconds were spent on a total of 13 queries. Zlib compression enabled.

Search the board with:
superb Board Search
or try with google:
Google
Web kixtart.org