简体   繁体   English

使用 shell(bash)-script 从文件中导出带有 substring 的字符串

[英]export string with substring from file with shell(bash)-script

I have file variables.tf :我有文件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 .我想用注释之类的描述为导出变量名称编写脚本,到文件terraform.tfvars But first line must be #description , and second line variable with empty value and double quotes , like this:但第一行必须是#description ,第二行变量必须是空值和双引号,如下所示:

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:我尝试像这样编写 bash 脚本test.sh

#!/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但是当我显示文件terraform.tfvars值行是第一行,描述行是第二行但必须相反

do_token  = ""
#set DO token value 

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

how i can do this properly?我怎么能正确地做到这一点? Thanks谢谢

This whole program is better implemented in awk itself.整个程序在 awk 本身中实现得更好。 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: ...发射为 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/S8Fmz1https://ideone.com/S8Fmz1的在线沙箱中查看此内容

If sed is an option如果sed是一个选项

$ 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 = ""

You could just move the line你可以移动这条线

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

after the line行后

echo "#"$DESCRIPTION >> terraform.tfvars

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

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