Command-Line

顯示匹配模式的行和每行之前的 4 行

  • October 13, 2011

例如,從此文件中:

CREATE SYNONYM I801XS07 FOR I8010.I801XT07
              *
ERROR at line 1:
ORA-00955: name is already used by an existing object


CREATE SYNONYM I801XS07 FOR I8010.I801XT07
              *
ERROR at line 1:
ORA-00955: name is already used by an existing object



Table altered.


Table altered.


Table altered.


Table altered.


Table altered.


Table altered.


Table altered.


Table altered.

DROP INDEX I8011I01
          *
ERROR at line 1:
ORA-01418: specified index does not exist



Index created.

我想要一種方法來查找ORA-並顯示該ORA-行和前 4 行:

CREATE SYNONYM I801XS07 FOR I8010.I801XT07
              *
ERROR at line 1:
ORA-00955: name is already used by an existing object

CREATE SYNONYM I801XS07 FOR I8010.I801XT07
              *
ERROR at line 1:
ORA-00955: name is already used by an existing object

DROP INDEX I8011I01
          *
ERROR at line 1:
ORA-01418: specified index does not exist

假設您使用的是舊系統,例如 HP-UX,它沒有 GNU 實用程序,只有舊的、原始的 BSD 或 AT&T “grep”。你可以這樣做:

#!/bin/sh

awk '/ORA-/ { print line1; print line2; print line3; print line4; print $0 }\
// {line1 = line2; line2 = line3; line3 = line4; line4 = $0}' $1

是的,有很多邊緣條件不正確,但是你想要什麼?此外,考慮到您正在使用一些經過解碼的、過時的作業系統和硬體,您可能沒有 CPU 能力來處理花哨的錯誤。

-B選項正是這樣做的grepgrep -B 4 ORA- your_file

在沒有 GNU 的情況下grep,我改編了grymoire sed 教程grep4中的範例:

#!/bin/sh

# grepB4: prints out 4 lines before and the line including pattern
# if there is only one argument, exit

case $# in 
   1);;
   *) echo "Usage: $0 pattern";exit;;
esac;

sed -n '
'/"$1"/' !{
   # does not match - add this line to the hold space
   H
   # bring it back into the pattern space
   x
   # Two lines would look like .*\n.*
   # Three lines look like .*\n.*\n.*
   # Delete extra lines - keep four
   s/^.*\n\(.*\n.*\n.*\n.*\)$/\1/
   # put it back in hold space
   x
}
'/"$1"/' {
   # matches - append the current line
   H
   # bring hold space contents into pattern space
   g
   # print the 4 lines
   p
   # add the mark
   a\
---
}'

用法:grepB4 pattern < file

Bruce Ediger 的回答與 . 基本相同awk,它的語法通常比sed.

引用自:https://unix.stackexchange.com/questions/22419