我有一个包含以下输出的文件。
ora.abc.db
1 ONLINE ONLINE serverA Open
2 ONLINE ONLINE serverB Open
ora.xyz.db
1 ONLINE ONLINE serverA Open
2 ONLINE ONLINE serverB Open
2 ONLINE ONLINE serverC Open
我想用以下方式格式化这个文件,但我只想使用shell script
,我相信我们可以使用 awk 但我没有逻辑
abc abc1 ONLINE serverA
abc abc2 ONLINE serverB
xyz xyz1 ONLINE serverA
xyz xyz2 ONLINE serverB
xyz xyz3 ONLINE serverC
答案1
这可以是一种方法:
$ awk '/^ora/ {split($0,a,"."); next} {print a[2], a[2]$1, $2, $4}' a
abc abc1 ONLINE serverA
abc abc2 ONLINE serverB
xyz xyz1 ONLINE serverA
xyz xyz2 ONLINE serverB
xyz xyz2 ONLINE serverC
解释
/^ora/
适用于以 . 开头的行ora
。其中,split
内容基于点.
并将其存储在数组中a
。所以它是a[1]=ora
,a[2]=abc
, ... 然后next
跳转awk
到下一行。print
打印数组的第二个字段a
以及该行中的不同元素:$1
声明第一个字段,$4
声明第四个字段。
答案2
稍微扩展(但基本等效)的脚本:
{
if($0 ~ /^ora/) { # look for lines starting (^) with "ora"
split($0, temp, "."); # find the elements of the line an put in array
serverName = temp[2]; # the "middle bit" - what was found between two dots
next; # nothing else to do with this line
}
else {
print serverName, serverName$1, $3, $4; # string together the bits
# note that each $n corresponds to the nth "word"
# by default fields are separated by white space
# you can set the variable FS to something else (e.g. FS=",")
# to deal with other formate
}
}
将其放入文件中server.awk
,如果您的输入位于 中log.txt
,则使用以下命令调用它
awk -f server.awk log.txt
我希望解释能增加一些价值......