Worked example - Reversing the order of lines of text in a file

How the need to convert a script for creating database views into a script to drop them led me to a useful powershell snippet

·

3 min read

I recently wanted to reverse the order of lines in a block of code, and thanks to superuser.com I found a way to do this with powershell.

Why I wanted to reverse the text in a file

I had an existing SQL script which created a number of database views. I wanted to generate a script which would drop the views. However, the views are interrelated so cannot be dropped in a random order. The script must ensure that we don't attempt to drop a view before first dropping all the views which depend upon it.

I use JetBrains Rider as an IDE, and this is how I used it to get a list of views to drop:

  1. Opened the existing script for creating the views.
  2. Used the regex search (CTRL+F, then enable regex with ALT+X) to find all uses of CREATE OR ALTER VIEW (.*) in the existing script
  3. Used the incredible helpful Select All Occurrences tool to select the lines of SQL which create the views.
  4. Copied and pasted these lines into a separate text file.

This gave me a file which looked like this:

CREATE OR ALTER VIEW Foo
CREATE OR ALTER VIEW Bar -- imagine this depends on Foo
CREATE OR ALTER VIEW Baz -- imagine this depends on Bar and Foo
-- etc

Changing CREATE OR ALTER VIEW to DROP VIEW IF EXISTS is trivial using find and replace, but I need to drop the Baz view before I could drop Bar, which needed dropping before I can drop Foo. For three lines it's trivial to manually reorder them, but this was a lengthy script containing many views.

How would you reverse the order of the lines of SQL to ensure that the views were dropped in an appropriate order?

How I reversed the order of lines

After a quick search online, I came across a powershell command that did exactly what I needed. Here it is:

$x = Get-Content -Path "drop views.txt"; Set-Content -Path "drop views reversed.txt" -Value ($x[($x.Length-1)..0])

Modified from How to reverse a text file on Windows

I created a file called drop views.txt which contained my SQL statements. Running the powershell command in the same folder creates a new file drop views reversed.txt which contains the same SQL statements, but in reverse order. If I'd wanted to modify the existing file I would simply have provided the same path to Set-Content as I had to Get-Content, so the command would have been:

$x = Get-Content -Path "drop views.txt"; Set-Content -Path "drop views.txt" -Value ($x[($x.Length-1)..0])

This approach worked completely, and the script to DROP the views ran without a hitch.

How would you have approached this problem?