7

How do I reverse the contents of a .txt file while preserving empty lines?

For example,

text one

text two
text three

text four


text five


text six

would become

text six


text five


text four

text three
text two

text one

Preferably with the Windows console or also source code to compile from to an application. I have Windows 7.

5

6 Answers 6

13

This can be done easily with PowerShell without any additional tools:

$x = Get-Content -Path data.txt; Set-Content -Path data.txt -Value ($x[($x.Length-1)..0])
3

Another PowerShell example. This just shows reversing. It would be trivial to export $x to a file.

$x = Get-Content -Path .\abc.txt
[array]::Reverse($x)
$x
2

I found the perfect tool for this: tac (part of CoreUtils for Windows)

1
  • 1
    Please read How to recommend software for minimum required information and other suggestions on how to recommend software on Super User. To keep your answer useful even if included link(s) breaks please edit these details into your answer. Nov 21, 2018 at 17:27
0

I would read the file in reverse order (using a script, program, etc.) and write it to a 'new' file thus avoiding a sort. Then, delete the 'old' file and rename the 'new' one to the 'old' one.

0

In most cases a typical sort won't preserve your empty lines, but it will instead place them all together somewhere in your sort. If it was me I'd just copy and paste the lines in Excel and sort there if it's just some one-off thing. Otherwise you'll be getting into some really fancy scripting to do this (but hey, it's possible to do).

As for the script I'd first have some code that searches for blank lines and saves that location to an array. Then I'd sort the rest of the data, either using some built-in sort method or making my own "bubble sort" code. Once sorted, reintroduce the line breaks at the locations given and you'll be set.

0

Here's something native - a VBScript script (.vbs).

Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
infile = Wscript.Arguments(0)
Set objTextFile = objFSO.OpenTextFile (infile, ForReading)
strText = objTextFile.ReadAll
objTextFile.Close
arrText = Split(strText, vbCrLf)
for l = ubound(arrText)-1 to 0 step -1
   wscript.echo arrText(l)
Next

Save it as (e.g.) revfile.vbs and run it using the cscript engine. As written, it echoes output to the console. To write the reversed lines to a file, use the > (redirection) operator like this:

cscript //nologo revfile.vbs "input.txt" > "output.txt"

Use quotes around the file names/paths if they have spaces.

C:\Test>type input.txt
apple
bear
cat
dog
egg
fog
gas
hip

ink
joe
kilo

C:\Test>type output.txt
kilo
joe
ink

hip
gas
fog
egg
dog
cat
bear
apple

You must log in to answer this question.

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