JQ:如何根据正则表达式匹配替换键和值? [英] JQ: How do I replace keys and values based on regex match?

查看:106
本文介绍了JQ:如何根据正则表达式匹配替换键和值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个问题:


  1. 我如何使用jq搜索以下划线开头的名称字段(例如 _RDS_PASSWORD )并删除开头的下划线(因此它变为 RDS_PASSWORD

  1. How can I use jq to search for "name" fields that start with an underscore (like _RDS_PASSWORD) and remove the leading underscore (so it becomes RDS_PASSWORD)

如何将jq用于以下划线开头的名称字段(例如 _RDS_PASSWORD )并传递值 cGFzc3dvcmQK 是否可以通过base64解码? (例如: cGFzc3dvcmQK | base64 --decode)

How can I use jq for "name" fields that start with an underscore (like _RDS_PASSWORD) and pass the value of the value cGFzc3dvcmQK to be decoded via base64? (ex: "cGFzc3dvcmQK" | base64 --decode)

输入:

[ 
  { 
    "name": "RDS_DB_NAME", 
    "value": "rds_db_name" 
  }, 
  { 
    "name": "RDS_HOSTNAME", 
    "value": "rds_hostname" 
  }, 
  { 
    "name": "RDS_PORT", 
    "value": "1234" 
  }, 
  { 
    "name": "RDS_USERNAME", 
    "value": "rds_username" 
  }, 
  { 
    "name": "_RDS_PASSWORD", 
    "value": "cGFzc3dvcmQK" 
  } 
]

所需的输出:

[ 
  { 
    "name": "RDS_DB_NAME", 
    "value": "rds_db_name" 
  }, 
  { 
    "name": "RDS_HOSTNAME", 
    "value": "rds_hostname" 
  }, 
  { 
    "name": "RDS_PORT", 
    "value": "1234" 
  }, 
  { 
    "name": "RDS_USERNAME", 
    "value": "rds_username" 
  }, 
  { 
    "name": "RDS_PASSWORD", 
    "value": "password" 
  } 
]


推荐答案

Q1



Q1

walk( if type=="object" and has("name") and .name[0:1] == "_"
      then .name |= .[1:]
      else . 
      end) 

如果您的jq没有 walk / 1 ,那么您可以升级到jq的1.5以上版本,或包含其 def ,可在 https://github.com/stedolan/jq/blob/master/src/builtin.jq

If your jq does not have walk/1 then you can either upgrade to a more recent version of jq than 1.5, or include its def, which can be found at https://github.com/stedolan/jq/blob/master/src/builtin.jq

.. | objects | select(has("name") and .name[0:1] == "_") | .value 

如果您确定编码字符串是UTF-8字符串,则可以使用jq @ base64d;否则,请使用-r选项调用jq,然后按照您的计划将结果通过管道传递给解码器。

If you are certain that the encoded string was a UTF-8 string, you could use jq's @base64d; otherwise, invoke jq with the -r option and pipe the results to a decoder as you indicated you planned to do.

这篇关于JQ:如何根据正则表达式匹配替换键和值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆