We help IT Professionals succeed at work.

Script needed to replace or add carriage return when seeing spefic text

I would like a simple script in .bat, .vbs, or powershell, which will look into a .txt fle and do one of the following, whichever is easier to do:

1.  Whenever it sees specific text such as AD, or DE, or BOG, or STOW..  that it will insert a tilde character (~) just before the text and then save the file with a new name.


2.  Whenever it sees the specific text such as AD, DE, BOG, or STOW, that it would start a new line which starts with those characters, and only start another line when it finds the next set of specific text.

The file resides at:  
And the output should be in the same folder but renamed to:
Watch Question

Test your restores, not your backups...
Expert of the Year 2019
Top Expert 2016
Here's a small VBS script approach.  Adjust the array to include strings to replace with a leading tilde.

It is in case sensitive replacement mode, if you want case insensitive change the last argument of the Replace() function from 0 to 1.

Const ForReading = 1
Const ForWriting = 2
Const TriStateUseDefault = -2

strInFile = "C:\Users\user\Desktop\folder\file.txt"
strOutFile = "C:\Users\user\Desktop\folder\fileR.txt"

arrSearch = Array("AD", "DE", "BOG", "STOW")

Set objFSO = CreateObject("Scripting.FileSystemObject")

With objFSO.OpenTextFile(strInFile, ForReading, False, TriStateUseDefault)
    strData = .ReadAll
End With

For Each strSearch in arrSearch
    strData = Replace(strData, strSearch, "~" & strSearch, 1, -1, 0)

With objFSO.OpenTextFile(strOutFile, ForWriting, True)
    .Write strData
End With

Open in new window

Most Valuable Expert 2019
Most Valuable Expert 2018

$inFile =  'C:\Users\user\Desktop\folder\file.txt'
$outFile = $inFile -replace '(?:\.)([^.]+)\Z', 'R.$1'
Get-Content -Path $inFile  ForEach-Object {$_ -creplace '(AD|DE|BOG|STOW)', '~$1'} | Set-Content -Path $outFile

Open in new window


Thanks very much.