awk Quick Help: printing upto 3rd octet .

Hi Experts,
I am trying to print $2 & the IP_address upto 3rd octet only.
But unable to do so, Trying

# awk '{print $2, substr($4,1,9)}' file

. but not correct

File:

HOST= cmiHOST06 :: 10.26.107.73:/data120 /nbu/cmiHOST06/athpx07/aa1
HOST= cmiHOST05 :: 10.26.12.76:/data120 /nbu/cmiHOST05/athpx07/cc1
HOST= cmiHOST05 :: 10.26.1.75:/data120 /nbu/cmiHOST05/athpx07/dd1

Output should be look like:

cmiHOST06 10.26.107
cmiHOST05 10.26.12
cmiHOST05 10.26.1

Thanks a lot,

awk '{ sub(/\.[0-9]+:.*/,x,$4); print $2, $4}' file
1 Like

bipinajith,
This worked great,
could you please explain a bit this portion , I am unable to unerstand how you got the 3 octet only outof 4 + ":" , with the

sub(/\.[0-9]+:.*/,x,$4);

Thanks,

---------- Post updated at 10:59 PM ---------- Previous update was at 10:54 PM ----------

Ok got it , that means the 4rth octet and remaining part of $4 substitured with x , that means with nothing value assigned to x, so $4 keeps upto 3rd octet only. Good one. Thanks.

1 Like

sub(/ - begin pattern

\. - starts with period .

[0-9]+ - followed by any number (one or more occurrence)

:.* - followed by colon : and zero or more occurance of any char

/,x,$4); - replace pattern with x which is undefined or null, end.

The above pattern actually matches below highlighted and remove them:

10.26.107.73:/data120

I hope this helps.

1 Like

This is awesome, able to understand now much better. bipinajith Thank you..

---------- Post updated at 11:09 PM ---------- Previous update was at 11:08 PM ----------

I also found another way with split:

awk '{split($4,x,"\.");print $2,x[1]"."x[2]"."x[3]}' file

---------- Post updated at 11:32 PM ---------- Previous update was at 11:09 PM ----------

Bipinajith,

How the regular expression can be formed if there is no ":" after the 4rth octet:
Below example:

file:

HOST= cmiHOST06    10.26.107.73 /data120 /nbu/cmiHOST06/athpx07/aa1
HOST= cmiHOST05    10.26.12.76 /data120 /nbu/cmiHOST05/athpx07/cc1
HOST= cmiHOST05    10.26.1.75 /data120 /nbu/cmiHOST05/athpx07/dd1

awk '{ sub(/\.[0-9]+$/,x,$3); print $2, $3}' file

1 Like