Wednesday, February 2, 2022

[SOLVED] Convert string in Shell

Issue

I have a following varaible:

tags = {
    environment  = "development",
    provider     = "ServiceOne",
    ansible_role = "nfs-role",
    comment      = "mysql"
}

In my pipeline i need to convert it to the following:

tfh pushvars -overwrite-all -dry-run false -hcl-var "tags={environment=\"development\", provider=\"ServiceOne\", ansible_role=\"nfs-rolep\",comment= \"mysql\"}"

I have tried with SED and AWK but couldn't get any result?

This is where i am standing now:

#!/bin/bash

#[[ -z "$2" ]] && echo "==> Usage: ./transform_tfe_vars.sh <<INPUT_FILE>> <<OUTPUT_FILE>>" && exit 1;

vars_file=${1}
#output_file=${2}
tmp_file=".todelete.tmp"

cmd "$vars_file" | grep -v '^#' | awk '!/^$/' > "$tmp_file"


while read -r p; do

    a=$(echo "$p" | awk '{print $1}')
    b=$(echo "$p" | awk '{print $3}')
    echo "tfh pushvars -overwrite-all -dry-run false -shcl-var \"$a=\\""$b""\""

done <$tmp_file

Solution

A shell read loop is always the wrong approach for manipulating text, see why-is-using-a-shell-loop-to-process-text-considered-bad-practice. The guys who invented shell also invented awk for shell to call to manipulate text.

It looks like this might be what you're trying to do:

#!/usr/bin/env bash

(( $# == 2 )) || { echo "==> Usage: ${0##*/} <<INPUT_FILE>> <<OUTPUT_FILE>>"; exit 1; }

vars_file="$1"
output_file="$2"

awk '
    BEGIN {
        ORS = ""
        print "tfh pushvars -overwrite-all -dry-run false -hcl-var \""
    }
    NF && !/^#/ {
        gsub(/[[:space:]]/,"")
        gsub(/"/,"\\\\&")
        print
    }
    END {
        print "\"\n"
    }
' "$vars_file" > "$output_file"


Answered By - Ed Morton
Answer Checked By - Robin (WPSolving Admin)