Home > Blockchain >  How to replace string after colon using sed, awk, regex, yq etc and can run using shell script
How to replace string after colon using sed, awk, regex, yq etc and can run using shell script

Time:09-13

I have a yaml file and in that file I need to replace a specific string that comes after oauth2accesstoken: using a shell script

my current shell script :-

#!/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"

File :-

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

Output Should be like this:-

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.

CodePudding user response:

With Go yq aka mikefarah/yq, its pretty straightforward to just select the right field and update its value

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

or pass the value from a shell variable

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

To modify the file in-place use the -i flag e.g. yq -i <rest-of-the-code>. Tested on version 4.27.5

CodePudding user response:

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

This will search for line with oauth2accesstoken and replace all after it.

  • Related