Edit lines in vbscript

Asked

Viewed 407 times

0

I am trying to learn VBS to resolve an issue that happened when I tried to import a file into my system. The file has more than 4000 lines and all lines must have 240 characters. (I don’t have backup)

Currently, the document is disfigured so:

The first line is ok, with 240.

The second line is only with CRLF. (0).

240 + 0 = 240

The third line is 238 characters + CRLF (238 characters).

The fourth line has 2 characters + CRLF (2 characters).

238 + 2 = 240

The fifth line is 236 characters + CRLF (236 characters).

The sixth line is 4 characters + CRLF (4).

236 + 4 = 240

The seventh line is 234 characters + CRLF (234 characters).

The eighth line has 6 characters + CRLF (6 characters).

234 + 6 = 240

I noticed that this pattern continues throughout the file, so I think I can fix it by VBS.

Could someone help me create a script to solve this problem?

I think I should read each line, use Len() to check the number of characters and give a DELETE where the CRLF would be if the line has less than 240 positions.

Or maybe split and concatenate the k line with the k+1 line, in a loop where k starts with 0 (line 1 of the file) and gets K = K+2 for each iteration.

I’ll try Split’s option first. If anyone wants to collaborate with some kind of code or just say a smarter way to solve the case, I’d appreciate it!

1 answer

0

Script vbs:

Dim arq
Dim obj

Set obj = CreateObject("Scripting.FileSystemObject")
Set arq = obj.OpenTextFile(WScript.Arguments(0), 1)

Dim texto
Dim conteudo
Dim tamanho

texto = arq.ReadAll
arq.Close
Set obj = Nothing

conteudo = Split(texto, vbCrLf)
tamanho = UBound(conteudo) - LBound(conteudo) + 1

Dim i
Dim numlinha

numlinha = 0
Do While numlinha < tamanho
    Dim novo
    novo = conteudo(numlinha)

    If Len(novo) < 240 Then
        Dim primeiralinha
        primeiralinha = numlinha
        Do While numlinha < tamanho And Len(novo) < 240
            numlinha = numlinha + 1
            novo = novo & conteudo(numlinha)
        Loop
        If Len(novo) <> 240 Then
            Err.Raise vbObjectError + 514, _
                "Erro concatenando linhas entre " & (primeiralinha + 1) & _ 
                " e " & (numlinha + 1) & " (inclusive)"
        Else
            WScript.Echo novo
        End If
    ElseIf Len(novo) > 240 Then
        Err.Raise vbObjectError + 515, _
            "Linha " & (numlinha + 1) & " tem mais de 240 caracteres"
    Else
        WScript.Echo novo
    End If

    numlinha = numlinha + 1
Loop

To use:

cscript script.vbs c:\dados\meuarquivo.txt > c:\dados\meunovoarquivo.txt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.