[ACCEPTED]-Powershell or Batch: find and replace characters-replace

Accepted answer
Score: 12

This should take care of it, using Powershell. This 10 can be done with straight cmd.exe stuff and some 9 built-in Windows executables, but it would 8 be far uglier and more difficult to comprehend.

It 7 will read in some file, and on each line:

  • replace [ with a
  • replace ] with o
  • replace | with u

The 6 escapes are needed since [, ], and | are all 5 special characters in powershell, and the 4 backtick ` is used to word-wrap commands.

$filename="textfile.txt"
$outputfile="$filename" + ".out"

Get-Content $filename | Foreach-object {
    $_ -replace '\[', 'a' `
       -replace '\]', 'o' `
       -replace '\|', 'u'
} | Set-Content $outputfile

If 3 you want to process a list of files, you 2 could set up an array to do this, and run 1 through the array.

$filenames = @("/path/to/File1.txt", "file2.txt", "file3.txt")
foreach ($file in $filenames) {
    $outfile = "$file" + ".out"

    Get-Content $file | Foreach-object {
        $_ -replace '\[', 'a' `
           -replace '\]', 'o' `
           -replace '\|', 'u'
    } | Set-Content $outfile
}

More Related questions