加入符合bash中特定条件的行

时间:2011-03-11 00:11:16

标签: bash sed

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

它可以在这样的文件上运行:

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而且我不知道如何解决这个问题:)

1 个答案:

答案 0 :(得分:2)

这是一个开始:

#!/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
}