grep一行然后打印awk直到某个子串

时间:2015-06-26 19:08:03

标签: linux shell awk scripting

我的代码是

var=$(cat $FILE | grep "$alineimlookingfor" | awk '{print $1, $2, $4, $7, $9... all the way to $20}'
echo "$var" 

但是,我希望在达到(0)或(1)之类的值时停止$ 9- $ 20。这将使我的输出格式看起来更好,因为(0)或(1)之后的任何东西都是垃圾。

有没有人对实现它的方法有所了解?

输入:

2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (0) - 21-JUNE-10    

输出:

2013-02-21 00:12:03,374 IN ProcedureTask - Finished Sales Summary 22 This (0)

编辑:感谢所有对这条线特别注意的人们,特别是对于他们来说,

1 个答案:

答案 0 :(得分:3)

更新

awk -v pattern="$alineimlookingfor" '
    $0 ~ pattern {
        rec = $1 OFS $2 OFS $4 OFS $7
        for (i=9; i<=NF; i++) {
            rec = rec OFS $i
            if ($i ~ /\([01]\)/) {
                break
            }
        }
        print rec
    }
' "$FILE"

完全符合您的要求

注意:

  • NF是一个awk变量,包含当前记录中 N F 字段数。
  • 当我们看到包含该模式的记录时:
    • 将前4个字段存储在名为rec的变量中,由 O 输出 F 字段 S eparator分隔。< / LI>
    • 遍历从9到最后的字段,附加到rec变量
      • 当我们看到一个匹配正则表达式(括号中为零或一个)时,我们就会突破for循环
    • 并打印累积的rec字符串。

首先,请注意awk可以执行catgrep所做的事情,因此我们可以立即简化管道

awk -v pattern="$alineimlookingfor" '$0 ~ pattern {print $1, $2, $4, $7, $9... all the way to $20}' "$FILE"

接下来,听起来你想要

awk -v pattern="$alineimlookingfor" '
    $0 ~ pattern {
        for (i=9; i<NF; i++) {
            if ($i == "(0)" || $i == "(1)") {
                NF = i
                break
            }
        }
        print
    }
' "$FILE"

这会更改“此记录中的字段数”变量,以便忽略后续字段。

测试

alineimlookingfor=ProcedureTask
awk -v pattern="$alineimlookingfor" '
    $0 ~ pattern {
        for (i=9; i<NF; i++) {
            if ($i == "(0)" || $i == "(1)") {
                NF = i
                break
            }
        }
        print
    }
' <<'END'
foo
2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (0) - 21-JUNE-10    
bar
2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (1) - 21-JUNE-10    
baz
2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (2) - 21-JUNE-10    
END

输出

2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (0)
2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (1)
2013-02-21 00:12:03,374 [Thread] IN ProcedureTask - Finished Sales Summary 22 This (2) - 21-JUNE-10