locked
reformat text file from single long line to multi line file based on length RRS feed

  • Question

  • I'm looking for a way with powershell to convert a single line text file to a multi lines text file.

    For example the input files has got fixed length records of 120 bytes but all of them have been concatenated to a single line file.

    My output file should contain multiple lines, each with 120 bytes.

    Can anyone help me get started on this ? 

    • Moved by Bill_Stewart Friday, March 15, 2019 6:26 PM This is not "scripts on demand"
    Friday, January 25, 2019 11:15 AM

All replies

  • Friday, January 25, 2019 1:13 PM
  • This is an interesting problem. There are several ways this could be done, but most require creating another file with the modified content. The following produces output that can be redirected to a new file, each lines no more than the maximum specified:

    $File = ".\InputFile.txt"
    $Lines = Get-Content -Path $File
    # Maximum line length.
    $LineLen = 100
    # Length of the line in the file now.
    $Length = $Lines.Length
    For ($j = 1; $j -le $Length; $j = $j + $LineLen)
    {
        If ($j + $LineLen -gt $Length) {$Line = $Lines.SubString($j-1)}
        Else {$Line = $Lines.SubString($j -1, $LineLen)}
        # Output the new line.
        $Line
    }
    


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Friday, January 25, 2019 2:23 PM
  • Thanks Richard, Indeed this is an interesting problem. Many files produced on Unix are single lined. In my case i have to transfer a file like this thru ftp to an iSeries computer which is not possible unless reformated.

    Your example does the job.

    Friday, January 25, 2019 2:38 PM
  • Great, glad it works.

    Richard Mueller - MVP Enterprise Mobility (Identity and Access)

    Friday, January 25, 2019 2:40 PM