Home > Enterprise >  export string with substring from file with shell(bash)-script
export string with substring from file with shell(bash)-script

Time:11-22

I have file variables.tf:

variable "do_token" {
  description = "set DO token value"
  type        = string
}

variable "ssh_pub_key_fingerprint" {
  description = "Set ssh key fingerprint stored in DO"
  type        = string
}

...

and i want to write script for export variables names with desctiptions like comment, to file terraform.tfvars. But first line must be #description, and second line variable with empty value and double quotes, like this:

cat terraform.tfvars

#set DO token value
do_token = ""

#Set ssh key fingerprint stored in DO
ssh_pub_key_fingerprint = ""

I tryed write bash script test.sh like this:

#!/bin/bash
echo -n "" > test.txt
grep 'description\|variable' variables.tf | while read line; do 
    OUTPUT=$(echo $line | sed 's/ =//g; s/ {//g' );
    # echo $OUTPUT
case "$OUTPUT" in 

  *description*)
    DESCRIPTION=$(echo $OUTPUT | awk -F "\"" '{print $2}')
    echo "#"$DESCRIPTION >> terraform.tfvars
    ;;

  *variable*)
    VARIABLE=$(echo $OUTPUT | awk -F "\"" '{print $2}')
    echo $VARIABLE " = \"\"">> terraform.tfvars
    ;;
esac    
done

but when i show file terraform.tfvars values line is a 1st, and description line 2nd but must be conversely

do_token  = ""
#set DO token value 

ssh_pub_key_fingerprint  = ""
#Set ssh key fingerprint stored in DO

how i can do this properly? Thanks

CodePudding user response:

This whole program is better implemented in awk itself. Given your input,

#!/bin/bash
gawk '
  BEGIN { first = 1 }
  /variable/ {
    curr_var = gensub(/"/, "", "g", $2)
  }
  /description = ".*"/ {
    if (first != 1) { printf("\n") }
    printf("%s = \"\"\n", curr_var)
    printf("#%s\n", gensub(/.*["]([^"] )["].*/, "\\1", $0))
    first=0
  }
'

...emits as output:

do_token = ""
#set DO token value

ssh_pub_key_fingerprint = ""
#Set ssh key fingerprint stored in DO

See this in the online sandbox at https://ideone.com/S8Fmz1

CodePudding user response:

If sed is an option

$ sed -n '/do_token/ {N;s/variable "\([^"]*\).*\n  description = "\([^"]*\).*/#\2\n\1 = ""\n/p};/ssh/{N;s/variable "\([^"]*\).*\n  description = "\([^"]*\).*/#\2\n\1 = ""/p}' input_file > terraform.tfvars
$ cat terraform.tfvars
#set DO token value
do_token = ""

#Set ssh key fingerprint stored in DO
ssh_pub_key_fingerprint = ""

CodePudding user response:

You could just move the line

echo $VARIABLE " = \"\"">> terraform.tfvars

after the line

echo "#"$DESCRIPTION >> terraform.tfvars
  • Related