Home > Net >  Replace string with line break with another string in Powershell
Replace string with line break with another string in Powershell

Time:04-08

I want to replace

$fieldTool.GetFieldValue($i
    tem,"Title")

with

{{(sc_get_field_value i_item 'Title')}}

The original string has a line break and I am using 'n like this $fieldTool.GetFieldValue($i'ntem,"Title")

This is the code

  $template = '<div >$fieldTool.GetFieldValue($i
  tem,"Title")</div>'
  $matchString = '$fieldTool.GetFieldValue($i'ntem,"Title")'
  $pattern = $([regex]::escape($matchString))
  $replaceString = "{{(sc_get_field_value i_item 'Title')}}"
  $newtemplate = $template -replace $pattern, $replaceString
  Write-Host $newtemplate

The above code is not working. How can I replace the string with line break with another string.

Any suggestion would be appreciated.

Thanks in advance

CodePudding user response:

To replace newlines, you should use regex pattern \r?\n. This will match both *nix as well as Windows newlines.

In your template string however, there are multiple characters that have special meaning in regex, therefore you need to do [regex]::Escape(), but that also would wrongfully escape the characters \r?\n, rendering it as \\r\?\\n, so adding that in the $matchString before escaping it, would be of no use.

You can manually first replace the newline with a character that otherwise is not present in the $matchString and has no special meaning in regex.

$template = '<div >$fieldTool.GetFieldValue($i
tem,"Title")</div>'
# for demo, I chose to replace the newline with an underscore
$matchString = '$fieldTool.GetFieldValue($i_tem,"Title")'
# now, escape the string and after that replace the underscore by the wanted \r?\n pattern
$pattern = [regex]::escape($matchString) -replace '_', '\r?\n'
# $pattern is now: \$fieldTool\.GetFieldValue\(\$i\r?\ntem,"Title"\)
$replaceString = "{{(sc_get_field_value i_item 'Title')}}"

# this time, the replacement should work
$newtemplate = $template -replace $pattern, $replaceString
Write-Host $newtemplate  # --> <div >{{(sc_get_field_value i_item 'Title')}}</div>
  • Related