1

I need to split up a very long line in a text file (maybe hundrerd thousands of characters) into shorter lines (8184 characters) and a .bat cannot handle this task.

However, I found a PowerShell solution (here):

(gc in.txt) -replace ".{750}" , "$&`r`n" | sc out.txt

This works when I open up the PowerShell window and paste the slightly adjusted version, where 750 is 8184 and execute it, BUT when including it in my .bat like this ...:

powershell -Command "(gc test.txt) -replace '.{8184}' , '$&`r`n' | sc temp.txt"

... it doesn't work as intended and inserts ...

`r`n

... after every 8184th character (I cannot inline format this, sry).


I tried to make use of:

powershell -Command "& {(gc test.txt) -replace '.{8184}' , '$&`r`n' | sc temp.txt}"

powershell -Command "(gc test.txt) -replace '.{8184}' , '$&\r\n' | sc temp.txt"

powershell -Command "(gc test.txt) -replace '.{8184}' , '$&VbCrLf' | sc temp.txt"

But I'm unable to make it work. What is the problem here?

2
  • Just so I'm clear here, you have a very long line in a text file, and you want to split it into shorter lines and save it to another file?
    – undo
    Commented Feb 7, 2018 at 19:20
  • @rahuldottech Yes. Commented Feb 7, 2018 at 19:20

1 Answer 1

3

`r`n is the correct escape sequence for a newline, but the problem is that single-quoted strings don't do the escape sequence evaluation or variable interpolation that double-quoted strings do, hence the literal escape sequence ending up in your output. We need to pass the string to PowerShell double-quoted, which is somewhat tricky since we have to deal with cmd.exe's interpretation as well. Using four double quotes per understood double quote does the job:

powershell -Command "(gc test.txt) -replace '.{8184}' , """"$&`r`n"""" | sc temp.txt"
2
  • How would I undo this with PowerShell itself? I tried several solutions I found and none of them appear to work... Commented Feb 11, 2018 at 18:48
  • 1
    @FatalBulletHit ((gc .\linebroken.txt) -join '') | sc .\oneline.txt should put it all back on one line.
    – Ben N
    Commented Feb 11, 2018 at 20:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .