我的代码是
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)
编辑:感谢所有对这条线特别注意的人们,特别是对于他们来说,
答案 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 字段数。rec
的变量中,由 O 输出 F 字段 S eparator分隔。< / LI>
rec
变量
for
循环rec
字符串。首先,请注意awk
可以执行cat
和grep
所做的事情,因此我们可以立即简化管道
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