Hey PowerShell Guy !, How Can I Replace Text That Includes Double Quote Marks and a Tab Character?
Some time ago but a new Hey Scripting Guy ! translation to PowerShell
How can I replace text that includes double quote marks and a tab character ?
the example given in this article is :
Speaking of which, let’s talk scripting for awhile. As we understand it, FC, you have a file (or maybe a bunch of files) that include this text, where the underscore represents the tab character:
rowsep="1">_
What you’d like to do is replace each of those values with this:
rowsep="1"><para>
For the complete example see the original article.
The PowerShell version looks like this :
$new = (Get-Content C:\Scripts\test.txt) -replace "(rowsep=`"1`">)`t", '$1<para>'
Set-Content C:\Scripts\test.txt $new
Some notes :
- to escape in PowerShell we use the Backtick character ( ` ), when we use sigle quotes we do not need to escape the Double Quotes but inside a Single quotes string we can not use escaped charaters like `t (meaning Tab) hence the use of Double quotes and the escaping of the double quotes.
- Next interesting point in this example is the use of Sub captures in the replacement, when we use the -Replace operator we can capture part of the original string by putting this part into parentheses (), the whole replacementstring is captured in the $0 variable and ever () block will get assigned to its own variable and will be numbered in this case $1 will contain the part of the original string we want to preserve (without the TAB )
- Same as in the original VbScript example we need to first save the new text into memory, we do that by assigning it to the $new variable and after that on the next line write this text back to the test.txt file.
- Also note that as the variable replacement of $1 is handled by the -Replace operator we do not need to use Double Quotes to resolve this variable.
Enjoy,
Greetings /\/\o\/\/