从最后一行删除逗号

时间:2014-04-10 21:02:33

标签: powershell

我正在尝试使用powershell从我的JSON输出中移除最后一个,我是Linux管理员,我会使用sed或awk来做到这一点,但我想知道如何使用PowerShell完成相同的任务。

{
    "data": [
        {
            "{#SERVICESTATE}": "Stopped",
            "{#SERVICEDISPLAY}": "Application Experience",
            "{#SERVICENAME}": "AeLookupSvc"
        },
       {
         "{#SERVICESTATE}": "Stopped",
         "{#SERVICEDISPLAY}": "Application Layer Gateway Service",
         "{#SERVICENAME}": "ALG"
    },  <--------- This is the comma I would like to remove from my output ---->
    ]
}

2 个答案:

答案 0 :(得分:3)

将-replace与多行正则表达式一起使用:

$JSON_Text = 
@'
{
    "data": [
        {
            "{#SERVICESTATE}": "Stopped",
            "{#SERVICEDISPLAY}": "Application Experience",
            "{#SERVICENAME}": "AeLookupSvc"
        },
       {
         "{#SERVICESTATE}": "Stopped",
         "{#SERVICEDISPLAY}": "Application Layer Gateway Service",
         "{#SERVICENAME}": "ALG"
    },  <--------- This is the comma I would like to remove from my output ---->
]


}
'@

$JSON_Text -replace '(?ms)(.+)(},)(.+)','$1}$3' 



{
    "data": [
        {
            "{#SERVICESTATE}": "Stopped",
            "{#SERVICEDISPLAY}": "Application Experience",
            "{#SERVICENAME}": "AeLookupSvc"
        },
       {
         "{#SERVICESTATE}": "Stopped",
         "{#SERVICEDISPLAY}": "Application Layer Gateway Service",
         "{#SERVICENAME}": "ALG"
    }  <--------- This is the comma I would like to remove from my output ---->
]


}

第一次捕获是&#34;贪婪&#34;,所以它会直接跑过第一个},然后停在最后一个。

答案 1 :(得分:0)

使用Get-Content(别名GC)加载文件,从最后开始,逐行退回查找逗号,并将其替换为找不到的内容。然后再次输出文件。

$file = gc c:\temp\test.txt
for($i = $file.count;$i -ge 0;$i--){if($file[$i] -match ","){$file[$i] = $file[$i] -replace ",";break}}
$file|out-file c:\temp\test.txt -force