我有一个YAML文件,其中也有列表。
YAML档案-
configuration:
account: account1
warehouse: warehouse1
database: database1
object_type:
schema: schema1
functions: funtion1
tables:
- table: table1
sql_file_loc: some_path/some_file.sql
- table: table2
sql_file_loc: some_path/some_file.sql我想将密钥对值存储到shell变量并循环执行。例如,帐户/仓库/数据库的值应该转到稍后我可以使用的变量。此外,表(table1和table2)和sql_file_loc的值应该转到shell变量,我可以使用该变量循环如下所示-
for i in $table ;do
echo $i
done我试过下面的密码-
function parse_yaml {
local prefix=$2
local s='[[:space:]]*' w='[a-zA-Z0-9_]*' fs=$(echo @|tr @ '\034')
sed -ne "s|^\($s\):|\1|" \
-e "s|^\($s\)\($w\)$s:$s[\"']\(.*\)[\"']$s\$|\1$fs\2$fs\3|p" \
-e "s|^\($s\)\($w\)$s:$s\(.*\)$s\$|\1$fs\2$fs\3|p" $1 |
awk -F$fs '{
indent = length($1)/2;
vname[indent] = $2;
for (i in vname) {if (i > indent) {delete vname[i]}}
if (length($3) > 0) {
vn=""; for (i=0; i<indent; i++) {vn=(vn)(vname[i])("_")}
printf("%s%s%s=\"%s\"\n", "'$prefix'",vn, $2, $3);
}
}'
}这是我得到的输出-
configuration_account="account_name"
configuration_warehouse="warehouse_name"
configuration_database="database_name"
configuration_object_type_schema="schema1"
configuration_object_type_functions="funtion1"
configuration_object_type_tables__sql_file_loc="some_path/some_file.sql"
configuration_object_type_tables__sql_file_loc="some_path/some_file.sql"它不打印- configuration_object_type_tables__table="table1“和configuration_object_type_tables__table="table2”
另外,对于一个列表,它会打印两个下划线(__),而不是其他对象。我想循环存储在configuration_object_type_tables__sql_file_loc.和configuration_object_type_tables__table中的值。
任何帮助都将不胜感激!
发布于 2022-11-05 11:43:20
考虑使用YAML处理器mikefarah/yq。只有一条线:
yq e '.. | select(type == "!!str") | (path | join("_")) + "=\"" + . + "\""' "$INPUT"输出
configuration_account="account1"
configuration_warehouse="warehouse1"
configuration_database="database1"
configuration_object_type_schema="schema1"
configuration_object_type_functions="funtion1"
configuration_object_type_tables_0_table="table1"
configuration_object_type_tables_0_sql_file_loc="some_path/some_file.sql"
configuration_object_type_tables_1_table="table2"
configuration_object_type_tables_1_sql_file_loc="some_path/some_file.sql"还请看一下yq的这个很酷的内置特性。
yq e -o props "$INPUT"输出
configuration.account = account1
configuration.warehouse = warehouse1
configuration.database = database1
configuration.object_type.schema = schema1
configuration.object_type.functions = funtion1
configuration.object_type.tables.0.table = table1
configuration.object_type.tables.0.sql_file_loc = some_path/some_file.sql
configuration.object_type.tables.1.table = table2
configuration.object_type.tables.1.sql_file_loc = some_path/some_file.sql发布于 2022-11-05 15:54:49
我建议你像刚才提到的那样试试yaml处理器。
关于这里的代码,regex与"- table“模式不匹配,原因是"- -”prifix。
https://stackoverflow.com/questions/74326520
复制相似问题