Home > Mobile >  How to substitute values in file between 2 strings
How to substitute values in file between 2 strings

Time:07-27

I want to replace the value between http:// and :80 dynamically everytime with a IP address that I am fetching. I have written below script to get the value and replace the placeholder 'localhost' with the IP address. But I want it to replace value betwen http:// and :80 and not by matching with localhost as it may change.

Line to substitute value in:

"UIApiPath": "http://localhost:80/uisvc/v1/api",
"serviceApiPath": "http://localhost:80/servicesvc/v1/api",
"DBApiPath": "http://locahost:80/DBsvc/v1/api"

Existing script for fetching and replacing value by matching 'localhost':

#!/bin/bash
DEPLOYMENT_NAME=$1
# Getting the pod name from the deployment object
GETTING_POD_NAME=$(kubectl describe deploy $1 | grep 'NewReplicaSet:' | awk '{print $2}')
# Getting the ip-address from pod description
echo ''
GETTING_IP_ADDRESS=$(kubectl describe pod $GETTING_POD_NAME | sed -n '4p' | awk '{print $2}')
# Getting the correct ip-address
SERVER_IP=${GETTING_IP_ADDRESS#*/}
echo $SERVER_IP
# Path of book-store-app configmap file:
APP_CONFIGMAP_FILE_PATH=deployment/java-apps/app-configmap.yaml
# Configure the ip-address in the configmap
sed -i "s/localhost/$SERVER_IP/g" $APP_CONFIGMAP_FILE_PATH


CodePudding user response:

Simple sed command based on // string:

sed "s#//[^:/]\ :80/#//$SERVER_IP:80/#" -i $APP_CONFIGMAP_FILE_PATH

Could do the job! (While $SERVER_IP variable don't hold any # character.)

Explanation

Note: Cited paragraph are copied from info sed pages.

  • s is normal replacment command under sed

    The syntax of the 's' command is 's/REGEXP/REPLACEMENT/FLAGS'.
    ...
    
  • # is used as command separator;

    The '/' characters may be uniformly replaced by any other single
    character within any given 's' command...
    
  • [^:/] mean any character, but no slashes / and no colons :.

    A "bracket expression" is a list of characters enclosed by '[' and ']'.
    It matches any single character in that list; if the first character of
    the list is the caret '^', then it matches any character *not* in the
    list.
    
  • * mean any number (even zero) of previous character (no slashes nor colons)

    '*'
        Matches a sequence of zero or more instances of matches for the
        preceding regular expression, which must be an ordinary character,
        a special character preceded by '\', a '.', a grouped regexp (see
        below), or a bracket expression. 
    ...
    '\ '
        As '*', but matches one or more.
    

I insist: Please read carefully info sed!

  • Related