Augusto
Augusto

Reputation: 13

how to replace a text with quotes

I need to replace the ' ",' to '",'. I need to remove all spaces but not the space in Abc CDE. In the end of each line there's also a space that I want to remove.

I was trying powershell but this doesn't work:

set "search=' ",'"
set "replace='",'"
:DoReplace
echo ^(Get-Content "aaa.TXT"^) ^| ForEach-Object { $_ -replace "%search%", "%replace%" } ^| Set-Content "New.txt">Rep.ps1
Powershell.exe -executionpolicy ByPass -File Rep.ps1

This is the example I use:

"0","46","","","","Abc CDE ApS                   ","","","","","81602832            ","","","","","","","","","","" 
"0","46","","","","Abc CDE ApS                   ","","","","","81602832            ","","","","","","","","","","" 
"0","46","","","","John Stewart                  ","","","","","85505637            ","","","","","","","","","","" 

Upvotes: 1

Views: 68

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

In PowerShell you could use a regular expression replacement like this:

(Get-Content 'aaa.txt') -replace ' +(",)','$1' | Set-Content 'aaa.txt'

but a much cleaner approach would be to import the file as a CSV and trim trailing spaces from each column, since the file seems to be a CSV anyway:

$csv = 'aaa.txt'
$outfile = 'bbb.txt'

# generate artificial headers
$cnt = @((Get-Content $csv -TotalCount 1) -split '","').Count
$headers = 1..$cnt | ForEach-Object { [string][char]($_+64) }

Import-Csv $csv -Header $headers | ForEach-Object {
  foreach ($prop in $_.PSObject.Properties) {
    $_.$($prop.Name) = $prop.Value.Trim()
  }
  $_
} | ConvertTo-Csv -NoType | Select-Object -Skip 1 | Out-File $outfile

With that said, for a batch approach (you should have mentioned that in your question) it would usually be much simpler to just use a Windows version of sed:

sed -i "s/ \+\",/\",/g" aaa.txt

Upvotes: 2

IkeRoyle
IkeRoyle

Reputation: 477

Is it that what you want?

$a = '"0","46","","","","Abc CDE ApS                   ","","","","","81602832            ","","","","","","","","","","" '

# delete all ' "'
While($a -like '* "*')
{
    $a = $a -replace ' "', '"'
}

# delete last character
$a = $a.subString(0,$a.length-1)

# whrite it into the console
echo ""
echo $a

Upvotes: 0

Related Questions