I am trying to replace the unnecessary double quotation marks in the names without a double quotation. For now, I know the names But I wanted the code to be dynamic. Any suggestions are greatly appreciated.
$FilePath = "C:\Test\"
Get-ChildItem $FilePath -Filter | ForEach-Object {
(Get-Content $_.FullName -Raw) | Foreach-Object {
$_ -replace ',"Frederick "Fred"",' , ',"Frederick Fred",' `
-replace ',"Brian "Josiah"",' , ',"Brian Josiah",' `
-replace ',""",' , ',"",'
} | Set-Content $_.FullName
}
CodePudding user response:
Use a regex:
# Sample input
$str = '"Frederick "Fred"","Brian "Josiah"",""""'
$str -replace '(?m)(?<=,|^)"([^,"]*)"([^,"]*)""(?=,|$)', '"$1$2"'
Output:
"Frederick Fred","Brian Josiah",""
For an explanation of the regex and the chance to experiment with it, see this regex101.com page (note that the "
chars. on the linked page are escaped as \"
, because the regex as a whole is enclosed in "..."
, unlike in '...'
, as above).
CodePudding user response:
here's a way to get rid of unwanted double quotes that does not use [mind melting for some of us] regex. [grin]
the code ...
$TwoDoubleQuotes = '""'
$OneDoubleQuote = '"'
$SpaceDQ = ' "'
$Space = ' '
$InString = '"Frederick "Fred"","Brian "Josiah"",""""'
$OutString = $InString.Replace($TwoDoubleQuotes, $OneDoubleQuote).Replace($SpaceDQ, $Space)
$InString
$OutString
the output ...
"Frederick "Fred"","Brian "Josiah"",""""
"Frederick Fred","Brian Josiah",""
what the code does ...
- defines some really simple minded constants
the string patterns are hard for me to read, so this bypasses that. [grin] - defines the inbound string
- chains the
.Replace()
string method
that replaces the2xDQ
with1xDQ
and then replaces theSpaceDQ
with just aSpace
. - saves the new string to a $Var
- displays both the old & new string for your viewing pleasure