我使用的是 AIX 6.1,它不支持 in-B
和-A
标志:
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
不会有任何输出。
答案1
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
答案2
我的做法略有不同。首先,运行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
答案3
$ awk -v RS= -F'\n' -v OFS='\n' '$1 ~ " OLTPF$"{for (i=1;i<=6;i++) print $i}' file
Database alias = OLTPF
Database name = OLTP
Node name = OLTPN
Database release level = 10.00
Comment =
Directory entry type = Remote