【问题标题】:sed for replacting special characters with ""sed 用“”替换特殊字符
【发布时间】:2021-06-11 23:00:54
【问题描述】:

我尝试像这样解析terraform output 的输出:

terraform output -json all_admins |
sed -e "s/,/;\n/g" -e "s/^(\[|\])//g"
terraform output -json all_admins

导致:

["admin1@admin.com","admin2@admin.com"]

当前结果:

terraform output -json all_admins |
sed -e "s/,/;\n/g" -e "s/^(\[|\])//g"

导致:

["admin1@admin.com";
"admin2@admin.com"]

预期结果:

"admin1@admin.com";
"admin2@admin.com"

如何使用 sed 中的正则表达式优雅地摆脱 []

【问题讨论】:

  • 使用 jq 或其他支持 JSON 的工具。
  • 我很乐意,但jq 没有安装在公司工作站上;)

标签: regex linux parsing sed


【解决方案1】:

仅使用您展示的示例,您能否尝试以下操作。使用 GNU awk 编写和测试。

terraform output -json all_admins | 
awk -v RS='\\[|,|\\]' 'NF{$0=$0(RT==","?";":"");print}'

显示示例输出如下。

"admin1@admin.com";
"admin2@admin.com"

说明: 将所有行的 RS(记录分隔符)设置为 [,]。然后在主程序检查条件如果字段数不为空且RT为,,则在当前行添加;,否则保持行不变,最后打印当前行。

【讨论】:

    【解决方案2】:

    你可以使用:

    terraform output -json all_admins | sed 's/[][]//g; s/,/;\
    /g'
    
    # Example:
    s='["admin1@admin.com","admin2@admin.com"]'
    echo "$s" | sed 's/[][]//g; s/,/;\
    /g'
    
    "admin1@admin.com";
    "admin2@admin.com"
    

    确保未转义的] 位于括号位置[...] 内的第一个位置,而[ 位于下一个位置。

    注意sed 's/[][]//g' file 等同于sed -E 's/\]|\[//g' file

    【讨论】:

    • 行得通,谢谢。你能解释一下为什么这个's/\]|\[//g' 有效,为什么我必须从] 开始吗?
    • 这是括号表达式的规则,未转义的] 必须在打开[ 之后立即放置,s/\]|\[//g 是交替,也可以写为's/\[|\]//g'
    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 2021-11-17
    • 1970-01-01
    相关资源
    最近更新 更多