2010-01-17 80 views
1

我是新来的Linux,我试图解析一堆文件看起来如下 -结肠分离子列表

  • 一些文本
    • 启动列表中的某些其他文本
      • 启动sublist1
      • continue sublist1
    • 个更多的元素
    • 更elements2
      • 一个sublist2
        • 子sublist1

凡列表之前所有的空间是标签。我需要一种方法来分析文本,这样一个冒号加为子列表...所以它看起来像在末尾以下内容:

  • 一些文字:
    • 启动列表中的某些其他文本:
      • 开始sublist1
      • 继续sublist1
    • 多个元素
    • 更elements2:
      • 一个sublist2:
        • 子sublist1
    • 另一元件

因此,当有冒号只添加一个可用的子列表。

我试图寻找到sed和awk的命令,但我无法找到保存的上线的状态,以便能够在末尾添加冒号什么。它不必在sed或awk中完成,我一直在尝试这些,但没有运气。任何建议都会有所帮助。

+0

将此标记为已回答如何? – stacker 2010-01-18 08:06:30

回答

1

财产以后像前人的精力解决您的问题:

awk ' 
    function countTabs(line) { 
     tabs=0; 
     i=0; 
     while(substr(line,i++,1) == "\t") 
      tabs++; 
     return tabs; 
    } 
{ 
    line1 = $0; 
    while(getline line2) { 
     if (countTabs(line1) < countTabs(line2)) 
      printf("%s:\n" , line1); 
     else 
      printf("%s\n",line1); 
     line1 = line2; 
    } 
    print line2; 
}' 
+0

我必须改变引号周围的标签为双引号,以使其适用于我:'“\ t”'但+1不使用数组(-1/2为制表符特定而不是任何白色 - 空间)。 – 2010-01-17 14:34:06

+0

我修正了qoute issu,谢谢。空格的问题是还需要制表符来计算缩进。问题是关于如何保持前一行。 – stacker 2010-01-17 14:48:15

+0

非常感谢,这非常有帮助。 :) – 2010-01-18 04:48:07

1

一些尝试

awk ' 
{ 
    A[d++]=$0 
    match($0,"[^[:blank:]]") 
    if (RSTART > t){ A[d-1]=A[d-1]":" } 
    else{ gsub(/:$/,"",A[d-2]) } 
    t=RSTART 
} 
END{ 
    for(i=0;i<=d;i++){ 
     print A[i] 
    } 
} ' file 

输出

$ cat file 
Some text 
     start list some other text 
       start sublist1 
       continue sublist1 
     more elements 
     more elements2 
       a sublist2 
         a sub-sublist1 
           a sub-sublist2 
     another element 

$ ./shell.sh 
Some text: 
     start list some other text: 
       start sublist1 
       continue sublist1 
     more elements 
     more elements2 
       a sublist2: 
         a sub-sublist1: 
           a sub-sublist2 
     another element 
+0

“更多elements2”应该在它后面有一个冒号,但它没有得到一个冒号。 – 2010-01-17 13:53:40

+0

用于匹配和RSTART的+1(使用数组时为-1/2) – 2010-01-17 14:35:59

0

ghostdog74的脚本这个修改后的版本应该把工作做好:

awk ' 
{ 
    A[NR]=$0 
    match($0,"[^[:blank:]]") 
    if (RSTART > t){ A[NR-1]=A[NR-1]":" } 
    t=RSTART 
} 
END{ 
    for(i=1; i<=NR+1; i++){ 
     print A[i] 
    } 
} ' file