我有下面的字符串,每行由换行作为输入字符串分隔
string="name: MAIN_ROLE
description: ROLE DESCRIPTION
readOnly:
roleReferences:
- roleTemplateAppId: app1
roleTemplateName: template2
name: Name1
- roleTemplateAppId: app2
roleTemplateName: template2
name: Name2
"
我喜欢将 YAML 字符串打印成逗号分隔的字符串,如下所示。输入字符串在“-”之后可以有任意数量的组件,这会产生新记录,但 MAIN_ROLE 值保持相同的第一列:
MAIN_ROLE,Name1,template1,app1
MAIN_ROLE,Name2,template2,app2
我在下面的代码中尝试用“-”分割行,但我没有得到正确的结果
echo "$a" | sed -n $'/^- $/,/^- $/p' <<< $string
最佳答案
您可以这样使用 awk
:
awk 'NR==1{a=$2;cnt=0} /^-/{rta[cnt]=$3;getline;rtn[cnt]=$2; getline; n[cnt]=$2;cnt++} END{ for(i=0;i<cnt;i++) { print a","n[i]","rtn[i]","rta[i] } }' file > outputfile
参见 online demo :
#!/bin/bash
string="name: MAIN_ROLE
description: ROLE DESCRIPTION
readOnly:
roleReferences:
- roleTemplateAppId: app1
roleTemplateName: template1
name: Name1
- roleTemplateAppId: app2
roleTemplateName: template2
name: Name2
"
awk 'NR==1{ # When on Line 1
a=$2;cnt=0 # Set a (main name) and cnt (counter) vars
}
/^-/{ # When line starts with -
rta[cnt]=$3; getline; # Add role template app ID to rta array, read next line
rtn[cnt]=$2; getline; # Add role template name to rtn array, read next line
n[cnt]=$2;cnt++ # Add name to n array, increment the cnt variable
}
END{ # When the file processing is over
for(i=0;i<cnt;i++) { # Iterate over the found values and...
print a","n[i]","rtn[i]","rta[i] # print them
}
}' <<< "$string"
# => MAIN_ROLE,Name1,template1,app1
# MAIN_ROLE,Name2,template2,app2
关于shell - 使用 sed 无法使用 "- "分隔符拆分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69665845/