shell - 使用 sed 无法使用 "- "分隔符拆分字符串

标签 shell sed split

我有下面的字符串,每行由换行作为输入字符串分隔

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/

相关文章:

java - 如何将 bash 脚本的输出打印到 Java 标准输出

regex - sed 用正则表达式替换 bbcodes

bash - 用 | 分割字符串Bash 中的字符并从第一行导出环境变量

linux - 如何在 2-3 行匹配模式之前插入一行

shell - 在视觉选择上运行 shell 命令

python - 如何使用 python -m json.tool 包含\n

regex - 使用 sed 在 cygwin 中替换 ""string"\1\"787"到 "string"\1\"787"

c++ - 在 C++ 中按空格拆分字符串的最快方法

python - pandas str.split给我一个意想不到的语法错误

MySQL 拆分列中的分号,为每个拆分形成一个新行