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

100questions
100questions used Ask the Experts™
on
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.

OR

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:  
C:\Users\user\Desktop\folder\file.txt
And the output should be in the same folder but renamed to:
C:\Users\user\Desktop\folder\fileR.txt
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
IT / Software Engineering Consultant
Top Expert 2016
Commented:
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
    .Close
End With

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

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

Open in new window


»bp
Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
PowerShell:
$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

Author

Commented:
Thanks very much.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial