首页 > 解决方案 > 如何并排打印输出?

问题描述

我从脚本得到以下输出:

192.168.0.10
192.168.0.10
undefined
192.168.0.130
192.168.0.130
ansible
192.168.0.141
192.168.0.141
undefined
192.168.0.252
192.168.0.252
undefined

但我希望它像:

192.168.0.10 192.168.0.10 undefined
192.168.0.130 192.168.0.130 ansible
192.168.0.141 192.168.0.141 undefined
192.168.0.252 192.168.0.252 undefined

我已经看到如何让 2 行彼此相邻,但我在 3 处失败 ^^

awk '{getline b;printf("%s %s\n",$0,b)}'

标签: awk

解决方案


awk请您尝试以下操作。

awk '{count++;printf("%s%s",$0,count%3==0?ORS:OFS)} END{if(count%3!=0){print ""}}' Input_file

说明:为上述代码添加详细说明。

awk '                                       ##Starting awk program from here.
{
  count++                                   ##Increasing variable count value with 1 here.
  printf("%s%s",$0,count%3==0?ORS:OFS)      ##Printing current line and either new line(ORS) or space(OFS) based opon condition if count is divided by 3 or NOT.
}
END{                                        ##Starting END block for this awk code here.
  if(count%3!=0){                           ##Checking condition if count is NOT fully divided by 3 then do following.
    print ""                                ##Printing null variable here in case previous line was not having new line so to add it in last.
  }
}
'  Input_file                               ##Mentioning Input_file name here.

推荐阅读