Shell-Script
在 AIX 中 -A/-B 替換之後/之前的 Grep 行
我正在使用不支持 in
-B
和-A
flags 的 AIX 6.1:grep: Not a recognized flag: B
假設我想執行:
cat file | grep -E -B4 'Directory entry type.*Indirect' | grep "Database name" | awk '{print $4}'
如何在 AIX 中執行這種邏輯?
編輯
我的真實程式碼如下:
NAME_EXISTS=`db2 LIST DB DIRECTORY | grep -E -B5 'Directory entry type.*Remote' | grep "Database alias" | awk '{print $4}' | grep -i ${NAME} | wc -l` if [ ${NAME_EXISTS} -gt 0 ]; then db2 LIST DB DIRECTORY | grep -E -A5 "Database alias.*${NAME}" fi
這個想法是查找是否有一個名為的遠端數據庫
$NAME
,如果找到它-顯示開頭的 5 行Database alias.*${NAME}
。$NAME
中是獨一無二的Database alias
。
db2 LIST DB DIRECTORY
輸出是這樣的:System Database Directory Number of entries in the directory = 3 Database 1 entry: Database alias = OLTPA Database name = OLTPA Local database directory = /db2/data Database release level = 10.00 Comment = Directory entry type = Indirect Catalog database partition number = 0 Alternate server hostname = Alternate server port number = Database 2 entry: Database alias = OLTPF Database name = OLTP Node name = OLTPN Database release level = 10.00 Comment = Directory entry type = Remote Catalog database partition number = -1 Alternate server hostname = Alternate server port number = Database 3 entry: Database alias = ADMIN Database name = ADMIN Local database directory = /db2/data Database release level = 10.00 Comment = Directory entry type = Indirect Catalog database partition number = 0 Alternate server hostname = Alternate server port number =
NAME=OLTPF
輸出將是:Database alias = OLTPF Database name = OLTP Node name = OLTPN Database release level = 10.00 Comment = Directory entry type = Remote
因為
NAME=OLTPE
不會有輸出。
我會做的略有不同。首先,執行
db2 LIST DB DIRECTORY
命令並將其輸出保存到文本文件中。這樣,您無需多次重新執行它。然後,對於每個目標名稱,將名稱傳遞給收集相關行的 awk 腳本:## Run the db command tempfile=$(mktemp) db2 LIST DB DIRECTORY > "$tmpfile" ## I am assuming you will have a loop for the different target names for name in OLTPF OLTPA; do awk -v name="$name" '{ if(/Database alias/){n=$4; a[n]=$0; i=1} if (i<=6 && i>1){ a[n]=a[n]"\n"$0} i++; }END{if(name in a){print a[name]}}' $tempfile done
ed 可能會提供一種簡單的方法來完成這項任務。
如果我們可以假設只有一個匹配項,那麼可以替代您的管道,使用 ed 並消除不必要的 cat 和輔助 grep:
ed -s file <<\EOED | awk '/Database name/ {print $4}' /Directory entry type.*Indirect/-4,//p q EOED
如果有多個不重疊的匹配,可以使用 ed 的全域命令來標記它們:
ed -s file <<\EOED | awk '/Database name/ {print $4}' g/Directory entry type.*Indirect/-4,.p q EOED
為了展示重疊匹配的情況,假設我們正在匹配字元串
foo
,並且在第 7 行和第 9 行有匹配項,並且我們將每個匹配項的前三行作為上下文,輸出將如下所示:line 4 <--- context line 5 <--- context line 6 <--- context line 7 foo <--- matched line 6 <--- context <--- repeated line 7 foo <--- context <--- repeated line 8 <--- context line 9 foo <--- matched line 10 line 11