简体   繁体   English

如何使用 sed、awk、正则表达式、yq 等替换冒号后的字符串,并且可以使用 shell 脚本运行

[英]How to replace string after colon using sed, awk, regex, yq etc and can run using shell script

I have a yaml file and in that file I need to replace a specific string that comes after oauth2accesstoken: using a shell script我有一个 yaml 文件,在该文件中我需要替换 oauth2accesstoken 之后的特定字符串:使用 shell 脚本

my current shell script:-我当前的 shell 脚本:-

#!/bin/sh

password=$(gcloud auth print-access-token)

password="$password" yq -i '.stringData.creds |= "oauth2accesstoken:" + strenv(password)' /test.yaml

Lets Assume Replace Value is " abcdefg1234 "假设替换值为“ abcdefg1234

File:-文件:-

kind: Secret
metadata:
  name: cred
type: Opaque
stringData:
  creds: oauth2accesstoken:ya29.a0AJ8fv7hrWsNVlDaXa-j6IUwBRdxt6GDDXMu1234efrtyhAjPWx0uw0174 # dummy key

Output Should be like this:- Output 应该是这样的:-

kind: Secret
metadata:
  name: cred
type: Opaque
stringData:
  creds: oauth2accesstoken:abcdefg1234

Error:-错误:-

Error: unknown command ".stringData.creds |= \"oauth2accesstoken:\" + strenv(password)" for "yq"
Run 'yq --help' for usage.

Note: -Above keys are dummy keys.注意: - 上面的键是虚拟键。

With Go yq aka mikefarah/yq , its pretty straightforward to just select the right field and update its value使用 Go yq aka mikefarah/yq ,只需 select 正确的字段并更新其值即可

yq '.stringData.creds |= "oauth2accesstoken:abcdefg1234"' yaml

or pass the value from a shell variable或从 shell 变量传递值

token="abcdefg1234" yq '.stringData.creds |= "oauth2accesstoken:" + strenv(token)' yaml

To modify the file in-place use the -i flag eg yq -i <rest-of-the-code> .要就地修改文件,请使用-i标志,例如yq -i <rest-of-the-code> Tested on version 4.27.5在版本 4.27.5 上测试

sed 's/(oauth2accesstoken:).*/\1:abcdefg1234/g' input.txt

This will search for line with oauth2accesstoken and replace all after it.这将搜索带有 oauth2accesstoken 的行并在其后替换所有行。

front=$(sed -n '/creds/p' file | cut -d':' -f1-2)
back="abcdefg1234"

echo "${front}:${back}" >> file

cat > ed1 <<EOF
$
-1d
wq
EOF

ed -s file < ed1
rm -v ./ed1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM