首页 > 解决方案 > 如何在 bash 中 AWK 多列

问题描述

我在下面有这张表,它有多个列。我想要的是只打印第一列和第二列

下面的这个命令产生下表:

kubectl get ing -n my-namespace 


firstcolumn          secondcolumn        third columns
1                    test                value
3                    test2               value
2                    test3               value
5                    test4               value
6                    test                value

预期输出应该是:

firstcolumn          secondcolumn        
1                    test                
3                    test2               
2                    test3               
5                    test4               
6                    test                

这下面的命令只有awk第一列。

kubectl get ing -n my-namespace | awk '{ printf "%10s\n", $2 }'

awk第一列和第二列如何?

标签: awk

解决方案


请您尝试以下操作。这将打印第一个和第二个字段之间存在的相同空格。

awk '{match($0,/ +/);print $1,substr($0,RSTART,RLENGTH),$2}' Input_file

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

awk '                                        ##Starting awk program from here.
{
  match($0,/ +/)                             ##Usingawk match function which will match very first ALL spaces in current line.
  print $1,substr($0,RSTART,RLENGTH),$2      ##Now printing $1 then substring starting from RSTART to RLENGTH(which will have spaces in it) then 2nd field.
}
' Input_file                                 ##Mentioning Input_file name here.


或者,如果您不担心间距(我认为您担心 spacig),那么您可以简单地执行以下操作:

awk '{print $1,$2}'  Input_file

推荐阅读