【发布时间】:2013-10-06 23:30:07
【问题描述】:
好的,所以我在大约一周前asked a question 关于如何使用 sed 或 awk 提取两个空行之间的文本块,以及省略部分提取的文本。我得到的答案几乎满足了我的需求,但现在我正在做一些额外的事情来娱乐(为了强迫症)。
我想在这一轮中对 awk 的输出进行排序。我找到了this question & answer,但它并不能帮助我解决问题。我也尝试过大量的 awk 文档,试图弄清楚如何做到这一点,但无济于事。
所以这是我脚本中完成所有脏工作的代码块:
# This block of stuff fetches the nameservers as reported by the registrar and DNS zone
# Then it gets piped into awk to work some more formatting magic...
# The following is a step-for-step description since I can't put comments inside the awk block:
# BEGIN:
# Set the record separator to a blank line
# Set the input/output field separators to newlines
# FNR == 3:
# The third block of dig's output is the nameservers reported by the registrar
# Also blanks the last field & strips it since it's just a useless dig comment
dig +trace +additional $host | \
awk -v host="$host" '
BEGIN {
RS = "";
FS = "\n"
}
FNR == 3 {
print "Nameservers of",host,"reported by the registrar:";
OFS = "\n";
$NF = ""; sub( /[[:space:]]+$/, "" );
print
}
'
如果我将google.com 作为$host 的值传入,这是输出(其他主机名可能会产生不同行数的输出):
Nameservers of google.com reported by the registrar:
google.com. 172800 IN NS ns2.google.com.
google.com. 172800 IN NS ns1.google.com.
google.com. 172800 IN NS ns3.google.com.
google.com. 172800 IN NS ns4.google.com.
ns2.google.com. 172800 IN A 216.239.34.10
ns1.google.com. 172800 IN A 216.239.32.10
ns3.google.com. 172800 IN A 216.239.36.10
ns4.google.com. 172800 IN A 216.239.38.10
这个想法是,使用现有的 awk 块,或者将 awk 的输出通过管道连接到更多 awk、排序或其他任何东西的组合中,使用条件算法对该文本块进行排序:
if ( column 4 == 'NS' )
sort by column 5
else // This will ensure that the col 1 sort includes A and AAAA records
sort by column 1
我对答案的偏好与上一个问题几乎相同:
- 最重要的是,它必须是可移植的,因为我在使用 sed 时遇到了 OS X(我的家庭系统)和 Fedora(我在工作中使用的)之间的不同行为(必须在 OS X 上用 gsed 替换它)和 grep 的 -m 标志(在另一个脚本中使用)
- 非常感谢您解释解决方案的工作原理,因为这是一个比其他任何东西都重要的学习机会。我已经从上一个问题中提供的 awk 解决方案中学到了很多东西。
- 如果解决方案可以在同一个 awk 块中实现,那也太棒了
- 如果不是,那么我可以通过管道传递 awk 的输出的简单而雄辩的东西就足够了
【问题讨论】:
-
传统的管道解决方案是添加,正如您所暗示的,另一个步骤是添加一个额外的 'type=1 (or type=2) 列和每一行的末尾,并且同时将所有记录类型重新格式化为可与
sort一起使用的通用格式(通过最简单的方式,可能在行的前面复制列)。来自sort的管道的最后一步是根据类型列恢复每一行的原始格式。祝你好运。 -
在这两种情况下,您都可以按
1,5排序,因为type=='NS'的字段1 是常量