将匹配字符串的输出从单独的行打印到输出文件的同一行

时间:2016-02-17 04:28:23

标签: awk grep

我在input.txt文件中有以下详细信息,我需要打印输出,如下所示。

input.txt

Name         = testserver1.net
IP-Address   = 10.0.0.1
OStype       = XPClient
Name         = testserver2.net
IP-Address   = 10.0.0.2
OStype       = Server2003

输出应该是这样的:

testserver1.net 10.0.0.1
testserver2.net 10.0.0.2

到目前为止,我这样做了:

 awk '/Name/ {print $3}; /IP/ {print $3}' input.txt

但是,我想以行格式打印输出,如上所述。

3 个答案:

答案 0 :(得分:1)

awk '/Name/ {printf "%s ",$3}; /IP/ {print $3}' file
testserver1.net 10.0.0.1
testserver2.net 10.0.0.2

答案 1 :(得分:1)

$  awk '/Name/{name=$3} /IP/{print name, $3}' input.txt
testserver1.net 10.0.0.1
testserver2.net 10.0.0.2

答案 2 :(得分:0)

使用sed:

$ sed -n '/testserver/{N;s/.*\(testserver\).*= \(.*\)$/\1 \2/p}' input.txt
testserver 10.0.0.1
testserver 10.0.0.2

详细说明(-n会阻止打印,除非明确指示):

/testserver/ {        # If we match 'testserver'
    N                 # Load the next line into pattern space

    # Substitution: only keep 'testserver' and what's after '=' on the next line
    # 'p' flag prints pattern space after substitution
    s/.*\(testserver\).*= \(.*\)$/\1 \2/p
}