[英]how to replace a text with quotes
我需要将' ",'
替换为'",'
。 我需要删除所有空间,但不能删除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 ","","","","","","","","","",""
在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
这就是你想要的吗?
$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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.