user53029
user53029

Reputation: 695

AWK: new column not aligning properly

Using awk to create a new column of data in a text file after the last column. My last column is mostly IP addresses but could be some text lines and looks like this:

192.168.50.25
192.168.111.145
Unknown

The command I am using to create the new column is:

 grep '102548' file | awk -v OFS='\t' '{print $0, "2018-10-22"}'

I am grepping for 102548 because I only want awk to work on the lines containing that string. Here is my output from the command:

192.168.50.25   2018-10-22
192.168.111.145         2018-10-22
Unknown         2018-10-22
172.16.15.145           2018-10-22

It seems to be no rhyme or reason as far as whats in the left column, but the new column layout, although not aligned and random, always takes this format

  2018-10-22
          2018-10-22
          2018-10-22
  2018-10-22
          2018-10-22

So it seems the "overlap" is always the same. How can I construct my command so that I always get this kind of separation?

 192.168.50.25        2018-10-22
 192.168.111.145      2018-10-22
 Unknown              2018-10-22
 172.16.15.145        2018-10-22

Upvotes: 1

Views: 690

Answers (1)

John1024
John1024

Reputation: 113834

The text on some lines in your first column extends past the first tabstop and, on other lines, it doesn't.

If you want things lined up in a visually nice way, try column -t:

$ awk '{print $0, "2018-10-22"}' file | column -t 
192.168.50.25    2018-10-22
192.168.111.145  2018-10-22
Unknown          2018-10-22

The above lines up columns based on any whitespace. If you want only tabs to separate columns (meaning that a column can include blanks), then try:

$ awk '{print $0, "2018-10-22"}' OFS='\t' file | column -s$'\t' -t
192.168.50.25    2018-10-22
192.168.111.145  2018-10-22
Unknown          2018-10-22

Upvotes: 2

Related Questions