如何用引号替换文本

时间:2015-10-09 08:36:59

标签: regex powershell

我需要将' ",'替换为'",'。我需要删除Abc CDE中的所有空格而不是空格。在每一行的末尾,还有一个我想删除的空间。

我正在尝试使用powershell,但这不起作用:

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

这是我使用的例子:

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

2 个答案:

答案 0 :(得分:2)

在PowerShell中,您可以使用正则表达式替换:

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

但更简洁的方法是将文件导入为CSV并修剪每列的尾随空格,因为该文件似乎仍然是CSV:

$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

话虽如此,对于批处理方法(你应该在你的问题中提到过),使用Windows版sed通常会简单得多:

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

答案 1 :(得分:0)

这就是你想要的吗?

    public class FooBarTest
    {
        public void DoSomethingWithFooBar<T>() where T : FooBarHolderAbstract<Foo, Bar>
        {
            //Do something tith the obj
        }

        public void RunTest()
        {                         
            DoSomethingWithFooBar<MyFooBarHolderImpl>();
        }
    }