2

I have this table below that has multiple columns. What I want is to print first and the second column only

this command below produces the below table:

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

expected output should be:

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

this below command only awk the first column.

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

how to awk both first and second columns?

2
  • 1
    so the value can contain space? for example, I see third columns with a space, can it occur on other columns too? Commented Apr 30, 2020 at 11:35
  • 3
    awk '{ printf "%10s\n", $2 }' does not print the 1st column, it prints the 2nd column (note the $2 as opposed to $1). Given that $2 means the 2nd column, is it obvious now how to print the 1st column too? If not - is that white space between your columns a single tab char or multiple blank chars or something else? Commented Apr 30, 2020 at 12:56

2 Answers 2

3

Could you please try following. This will print same spaces what is present between your 1st and 2nd fields.

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

Explanation: Adding detailed explanation for above code.

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.


OR in case you are NOT worried about spacing(which I think you are worried about spacig) then you can simply do:

awk '{print $1,$2}'  Input_file
Sign up to request clarification or add additional context in comments.

Comments

1

You can print the first two columns using, kubectl get ing -n my-namespace | awk '{ print $1, $2}'. By default, awk takes space as a column separator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.