匹配后使用{,/和“ sed替换一定数量的字符

时间:2019-01-03 14:43:39

标签: shell sed

我需要将\"db_password\":\"之后最多16个字符(密码)的内容替换为<sensitive>

data_json: "{\"db_password\":\"qwHLI?mkSrQ=GHU_\"}" => "{\"db_password\":\"BoBBsR9PA]wZ_3AC\"}"

应该是

data_json: "{\"db_password\":\"sensitive\"}" => "{\"db_password\":\"sensitive\"}"

我尝试遵循但不确定如何逃避{\"

sed -E 's/("{\"db_password\":\").{16}/\<sensitive>/'

1 个答案:

答案 0 :(得分:0)

cat jsonfile
#=> data_json: "{\"db_password\":\"qwHLI?mkSrQ=GHU_\"}" => "{\"db_password\":\"BoBBsR9PA]wZ_3AC\"}"

sed -E 's/("\{\\"db_password\\":\\").{16}/\1sensitive/g' jsonfile
#=> data_json: "{\"db_password\":\"sensitive\"}" => "{\"db_password\":\"sensitive\"}"

您也需要转义\。同样,\1引用第一对()匹配的内容。
<>在这里是不必要的。

更新:没有16个字符的密码限制:

sed -E 's/("\{\\"db_password\\":\\")[^"\]+/\1sensitive/g' jsonfile
#=> data_json: "{\"db_password\":\"sensitive\"}" => "{\"db_password\":\"sensitive\"}"

这将替换所有密码中的密码。 (那么,密码不能为\。)