【问题标题】:Joining lines that matches specific conditions in bash连接符合 bash 中特定条件的行
【发布时间】:2011-07-13 03:46:10
【问题描述】:

如果出现以下情况,我需要一个可以连接行的命令:
-下一行以超过 5 个空格开头
- 连接行的长度不会超过 79 个字符
- 这些线不在具有 pattern1 和 pattern2 的线之间
- 与上面相同,但有另一组模式,如模式 3 和模式 4

它适用于这样的文件:

Long line that contains too much text for combining it with following one  
That line cannot be attached to the previous becouse of the length
This one also 
becouse it doesn't start with spaces

This one 
     could be
     expanded

pattern1
here are lines
     that shouldn't be 
     changed
pattern2

Another line
     to grow

运行命令后,输出应该是:

Long line that contains too much text for combining it with following one  
That line cannot be attached to the previous becouse of the length
This one also 
becouse that one doesn't start with spaces

This one could be expanded

pattern1
here are lines
     that shouldn't be 
     changed
pattern2

Another line to grow

它不能移动部分行。

我正在使用 bash 2.05 sed 3.02 awk 3.1.1 和 grep 2.5.1,但我不知道如何解决这个问题 :)

【问题讨论】:

    标签: bash sed


    【解决方案1】:

    这是你的开始:

    #!/usr/bin/awk -f
    BEGIN {
            TRUE = printflag1 = printflag2 = 1
            FALSE = 0
    }
    
    # using two different flags prevents premature enabling when blocks are
    # nested or intermingled
    /pattern1/ {
            printflag1 = FALSE
    }
    
    /pattern2/ {
            printflag1 = TRUE
    }
    /pattern3/ {
            printflag2 = FALSE
    }
    
    /pattern4/ {
            printflag2 = TRUE
    }
    
    {
            line = $0
            sub(/^ +/, " ", line)
            sub(/ +$/, "", line)
    }
    
    /^     / &&
        length(accum line) <= 79 &&
        printflag1 &&
        printflag2 {
            accum = accum line
            next
    }
    
    {
            print accum
            accum = line
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-21
      • 2021-03-12
      • 1970-01-01
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多