简体   繁体   中英

Powershell replace with double quotes and new line

I wanna replace something with double quotes, but also need a new line in the middle. How can I do this? I tried all combinations, but it seems to me that a new line needs double quotes, is there any other way?

For example:

(Get-Content '.\input.xml') -replace 'version="1.0">', 'version="1.0"> "`n `n" iNeedANewLineHere' | Set-Content -encoding UTF8 '.\output.xml'

This way it doesnt interpret the nl-commands as new lines, it prints everything as text, in cause of the single quotes... is there any other way to solve this problem?

Use double quotes to enclose your string, and escape the inner double quotes as such:

(Get-Content '.\input.xml') -replace 'version="1.0">', "version=`"1.0`"> `"`n `n`" iNeedANewLineHere" | Set-Content -encoding UTF8 '.\output.xml'

Or like this:

(Get-Content '.\input.xml') -replace 'version="1.0">', "version=""1.0""> ""`n `n"" iNeedANewLineHere" | Set-Content -encoding UTF8 '.\output.xml'

If you are executing this from CMD you will need to escape any internal double quotes that you are trying to pass to PowerShell in CMD as they are passed. This should do that:

powershell -Command "(Get-Content '.\input.xml') -replace 'version=^"1.0^">', ^"version=^"^"1.0^"^"> `n `n iNeedANewLineHere^" | Set-Content -encoding UTF8 '.\output.xml'"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM