Using PowerShell, How Do You Reverse the Individual Strings in a .txt File While Preserving the Top to Bottom Order of the Lines Themselves?

Problem scenario
You have a list of strings in a .txt file.  You want each string to be in the reverse order from left to right.  You want the strings to remain in their current order from top to bottom.  In other words, you want the content of each line to be reversed. Otherwise you want to preserve the lines in the file (row by row).  For example, the file looks like this:

abc
def
ghi

You want the PowerShell script to transform the above list into this as a separate and new file:

cba
fed
ihg

How do you write such a program?

Solution
<# This program requires one input file, and this file is assigned to the variable "$mainfile".  Change the name and location of 'c:\temp\primarylist.txt' as desired.  The output file will be 'c:\temp\reversed.txt' unless you change it. #>

$mainfile = 'c:\temp\primarylist.txt'
$finalfile = 'c:\temp\reversed.txt'

function reverseString  #reverseString function taken from https://gist.github.com/arebee/ee72fed0a7b5eb90f380
{
  Param(
    [string]$str
  )

  $sb = New-Object System.Text.StringBuilder($str.Length)
  write-verbose $sb.Capacity

  for ($i = ($str.Length - 1); $i -ge 0; $i--)
  {
    [void]$sb.Append($str.Chars($i))
  }

  return $sb.ToString()
}

$transition = get-content $mainfile

$i = 0
$r = Get-Content $mainfile | Measure-Object –Line
$numline = $r.Lines
$coolarray = New-Object string[] $numline    # create an array with the number of lines in the file

foreach ($x in $transition) {      # reverse each line in the array
  $b = reverseString $x
  $coolarray[$i] =  $b
  $i = $i + 1
}

echo $coolarray > $finalfile

Leave a comment

Your email address will not be published. Required fields are marked *