Powershell or Batch: find and replace characters

16,794

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

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

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

The escapes are needed since [, ], and | are all special characters in powershell, and the 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 you want to process a list of files, you could set up an array to do this, and run 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
}
Share:
16,794
jjoras
Author by

jjoras

Updated on August 26, 2022

Comments

  • jjoras
    jjoras over 1 year

    I have ten text files (tab delimited, 200K rows). My intention is to seek characters [, ], | and replace them with a, o, u, respectively. Any hints how to do this using Windows batch script or Powershell?

  • Jaykul
    Jaykul over 13 years
    You really shouldn't use the () around the Get-Content unless you .absolutely have to edit the file in place -- it causes all the lines to be collected before replacing, which is going to be really expensive with large files