问题
I have a text file with the some special character $
, which needs to be replaced by double double quotes. I am using a bat file in which I invoke powershell.exe
and write the replace command. Below is the command:
powershell "gc C:\Temp\Test.csv| foreach-object {$_ -replace '$','""""""'}|sc C:\Temp\Test_Replace.csv"
I know that double quotes are escaped by a double quote so """"" is equivalent to "". But as seen in the above code I need to write 6 double quotes to get the equivalent 2 quotes. I cannot figure out the reason for this.
Can Someone please illustrate the point I am missing.
回答1:
As I said in comments, I think it is a but in PowerShell.exe
command line parser. When it see ""
inside quoted context, it not only produce literal "
but also close quoted context:
CMD> powershell '"1 2""3 4"'
1 2"3 4
As you can see, there is only one space between 3 in 4 in printed string. You need to put extra double quote to reopen quoted context:
CMD> powershell '"1 2"""3 4"'
1 2"3 4
So, in fact, you have to triplicate double quote to produce just one literal double quote character.
回答2:
You just need to escape the nested double quote properly. Also, the ForEach-Object
isn't required. Put the Get-Content
in an expression (i.e. in parentheses) and you can use the -replace
operator directly.
powershell -Command "(gc C:\Temp\in.csv) -replace '$','\"\"'|sc C:\Temp\out.csv"
If you want to replace literal $
characters instead of adding double quotes to the end of each line you need to escape the $
as well, as Mathias pointed out:
powershell -Command "(gc C:\Temp\in.csv) -replace '\$','\"\"'|sc C:\Temp\out.csv"
来源:https://stackoverflow.com/questions/35709045/replace-special-character-with-double-double-quotes