1

I am trying to convert the 3rd column as shown below. I can use this function to

convert ***awk '{print $3}'  | awk -F: '{printf("%02s:%02s:%02s:%02s:%02s:%02s\n",$1,$2,$3,$4,$5,$6)}'*** but how to get it to replace the 3rd column values.

Before 

ABC    22.22.28.97     0:0:c:9f:f0:d9

ABC    22.22.28.109    0:50:56:64:49:f3

ABC    22.22.28.110    0:50:56:68:55:8e

After

ABC    22.22.28.97     00:00:0c:9f:f0:d9

ABC    22.22.28.109    00:50:56:64:49:f3

ABC    22.22.28.110    00:50:56:68:55:8e

Thank you :)

  • 1
    I tried to replay your command line: convert ***awk '{print $3}' but I get an error: convert: unable to open image. Please tell me the exact command that you are giving. – user680858 May 4 '17 at 21:26
0

I think what you're asking is how to zero-pad the hexadecimal elements of the colon-separated string in the third field. That's (perhaps surprisingly) hard to do in awk because:

  1. the %s (string) format specifier doesn't support zero-padding (neither in awk nor in the underlying C function AFAIK)

and

  1. if you use the appropriate numeric format %02x then the arguments are implicitly converted as decimal digits first (discarding a-f as garbage) - resulting in incorrect hexadecimal values.

If you have GNU awk, you can manipulate and convert hex digits using the --non-decimal-data command line option, however the elements themselves need to be prefixed with 0x to force the conversion. So for example

gawk --non-decimal-data '
  gsub(/[[:xdigit:]][[:xdigit:]]?/,"0x&",$3) && split($3,a,":") {
    $3=sprintf("%02x:%02x:%02x:%02x:%02x:%02x",a[1],a[2],a[3],a[4],a[5],a[6])
  } 1' OFS='\t' file
ABC     22.22.28.97     00:00:0c:9f:f0:d9

ABC     22.22.28.109    00:50:56:64:49:f3

ABC     22.22.28.110    00:50:56:68:55:8e

It's somewhat simpler in perl where you can use the hex function and simple regex substitution:

perl -alne '$F[2] =~ s/([[:xdigit:]]{1,2})/sprintf "%02x", hex($1)/ge , print join "\t", @F' file
ABC     22.22.28.97     00:00:0c:9f:f0:d9

ABC     22.22.28.109    00:50:56:64:49:f3

ABC     22.22.28.110    00:50:56:68:55:8e
  • I found an easier answer sed 's/\b(\w)\b/0\1/g' file to work \b(between a word character and a non-word character). Thanks for the quick response. – joseph rob May 4 '17 at 23:50
0

I found an easier answer 's/\b(\w)\b/0\1/g' file. I want to use awk but sed has the \b (between a word character and a non-word character)

0
perl -pe 's/\b([0-9a-f](:|$))/0$1/g' ex
  • add a 0 before all the singular hexdecimal digits followed by ":" or end of line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.