Indented lines (tree) to path-like lines

后端 未结 2 516
失恋的感觉
失恋的感觉 2021-01-03 05:46

I have input files with the structure like the next:

a1
  b1
    c1
    c2
    c3
  b2
    c1
      d1
      d2
  b3
  b4
a2
a3
  b1
  b2
    c1
    c2
         


        
2条回答
  •  無奈伤痛
    2021-01-03 06:43

    interesting question.

    this awk (could be one-liner) command does the job:

    awk -F'  ' 'NF<=p{for(i=1;i<=p;i++)printf "%s%s", a[i],(i==p?RS:"/")
                if(NF

    you can see above, there are duplicated codes, you can extract them into a function if you like.

    test with your data:

    kent$  cat f
    a1
      b1
        c1
        c2
        c3
      b2
        c1
          d1
          d2
      b3
      b4
    a2
    a3
      b1
      b2
        c1
        c2
    
    kent$  awk -F'  ' 'NF<=p{for(i=1;i<=p;i++)printf "%s%s", a[i],(i==p?RS:"/")
    if(NF

提交回复
热议问题