[英]Split string with double quotes in PowerShell
我有一个类似行的文件,如下所示:
setmessage id=xxx.yyy.1 "text=Your input is not correct."
setmessage id=xxx.yyy.2 "text=Please add a ""Valid from"" date."
setmessage "id=xxx.yyy.3" "text=Another text, but the ID is in quotes too."
我的目标是将此文本拆分为不同的属性:
id => 'xxx.yyy.1'
text => 'Your input is not correct.'
id => 'xxx.yyy.2'
text => 'Please add a ""Valid from"" date.'
id => 'xxx.yyy.3'
text => 'Another text, but the ID is in quotes too.'
我目前使用的是这个:
function extractAttribute([String] $line, [String] $attribute){
if ($line -like "*$attribute*"){
$return = $line -replace ".*(?=`"$attribute=)`"$attribute=([^`"]*).*|.*$attribute=(.*?)([\r\n].*|$)", "`$1`$2"
if ($return -eq ""){
$return = $null
}
return $return
} else {
return $null
}
}
使用该代码,我可以一次提取一个属性。 但它不适用于双引号:
$line = 'setmessage id=xxx.yyy.2 "text=Please add a ""Valid from"" date."'
$attribute = "text"
$result = extractAttribute $line $attribute
结果是:
'Please add a '
其余的都不见了。 预期的结果应该是:
'Please add a ""Valid from"" date.'
有谁能帮助我吗?
谢谢!
编辑:我通过用其他东西替换坏的双引号创建了一个穷人的解决方案,然后拆分文本并再次替换。 不好,但有效:
function extractAttribute([String] $line, [String] $attribute){
if ($line -like "*$attribute*"){
$line = $line -replace '""', '~~'
$return = $line -replace ".*(?=`"$attribute=)`"$attribute=([^`"]*).*|.*$attribute=(.*?)([\r\n ].*|$)", "`$1`$2"
$return = $return -replace '~~', '""'
if ($return -eq ""){
return $null
} else {
return $return
}
} else {
return $null
}
}
您可以在没有功能的情况下进行此更改:
$line = 'setmessage id=xxx.yyy.2 "text=Please add a ""Valid from"" date."'
$attribute = "text="
$result=$line -replace ".*(?<=$attribute)" #select all to and of your attribute and replace it to nothing
附加(如果您从文件中读取数据) :
$pattern1="(?<=id=).*?((?=\s)|(?=`"))"
$pattern2="(?<=text=).*(?=`")"
$customdata=@()
$z=Get-Content D:\testdir\sample.txt |ForEach-Object{
$customdata+=[PSCustomObject]@{
ID=$_ |Select-String $pattern1|foreach{$_.Matches.value}
text=$_ |Select-String $pattern2|foreach{$_.Matches.value}
}
}
现在$customdata
是具有两个属性ID
和text
数组,您可以通过$customdata.ID
$customdata.text
从中获取数据。如果您需要编写一些输出,您可以在 foreach 循环中运行它并格式化您的输出。
我会考虑为此使用Import-Csv
cmdlet 或onvertFrom-Csv
cmdlet:
根据包含的<name>=<value>
格式设置属性Name
和Value
:
# Import-Csv .\Input.txt -Header (0..3) -Delimiter ' ' | ForEach-Object ...
$Content | ConvertFrom-Csv -Header (0..3) -Delimiter ' ' | ForEach-Object {
$Properties = @{}
ForEach ($Item in ($_.PSObject.Properties.Value).Where{$_}) {
$Name, $Value = $Item.Split('=',2)
$Properties[$Name.Trim()] = "$Value".Trim()
}
[pscustomobject]$Properties
} | Select-Object Id, Text
结果:
id text
-- ----
xxx.yyy.1 Your input is not correct.
xxx.yyy.2 Please add a "Valid from" date.
xxx.yyy.3 Another text, but the ID is in quotes too.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.