celcoprab
celcoprab

Reputation: 35

AWK to print subnet 0.69.100.in-abc.def

My requirement is to print a subnet 100.69.0.0/10 value to 0.69.100.in-abc.def. I tried as below

echo ['100.69.0.0/10'] | awk -F'.'  '{print $3"."$2"."$1".in-abc.def."}'

but i got output like this

0.69.[100.in-abc.def.

How to get output using awk as below

0.69.100.in-abc.def.

Upvotes: 1

Views: 75

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133428

Good attempt and you were close, try following. With OP's approach we need to put [ and ] as field separator too, so that we could catch the exact needed values by OP.

echo ['100.69.0.0/10'] | 
awk -F"[].[']" 'BEGIN{OFS="."} {print $4,$3,$2,"in-abc.def."}'

OR in case your echo is printing ['100.69.0.0/10'] then try following(where we have [,],.,' as field separators for awk):

echo "['100.69.0.0/10']" | 
awk -F"[].[']" 'BEGIN{OFS="."} {print $5,$4,$3,"in-abc.def."}'

Improvement in OP's code(attempt): OP has added only . as field separator to make things easy we could add [ and ] too in field separators so that we could get the exact needed values.

NOTE: 1st solution is assuming that OP's echo output is [100.69.0.0/10] which I believe could be wrong, OP's echo output may have ' like ['100.69.0.0/10'](when using " to cover echo's output) in that case kindly use 2nd solution in above.

Upvotes: 3

James Brown
James Brown

Reputation: 37394

How about doing it properly:

$ echo ['100.69.0.0/10'] | 
awk '
match($0,/([0-9]{1,3}\.){3}[0-9]{1,3}/) {           # match ip-ish looking string
    split(substr($0,RSTART,RLENGTH),t,/\./)         # split it on .
    printf "%s.%s.%s.in-abc.def.\n",t[3],t[2],t[1]  # printf it carefree
}'

Output

0.69.100.in-abc.def.

Upvotes: 2

Related Questions