azatuni
azatuni

Reputation: 43

how to add 0 digit to a single symbol hex value where it is missed, bash

I have a some file with the following content

$ cat somefile
28 46 5d a2 26 7a 192 168 2 2  
0 15 e c8 a8 a3 192 168 100 3
54 4 2b 8 c 26 192 168 20 3

As you can see the values in first six columns are represented in hex, the values in last four columns in decimal formats. I just want to add 0 to every single symbol hexidecimal value.

Thanks beforehand.

Upvotes: 3

Views: 168

Answers (4)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed 's/\b\S\s/0&/g' file

Finds a single non-space character and prepends a 0.

Upvotes: 0

Carl Norum
Carl Norum

Reputation: 224964

This one should work out for you:

while read -a line
do
    hex=(${line[@]:0:6})
    printf "%02x " ${hex[@]/#/0x}
    echo ${line[@]:6:4}
done < somefile

Example:

$ cat somefile 
28 46 5d a2 26 7a 192 168 2 2  
0 15 e c8 a8 a3 192 168 100 3
54 4 2b 8 c 26 192 168 20 3

$ while read -a line
> do
>     hex=(${line[@]:0:6})
>     printf "%02x " ${hex[@]/#/0x}
>     echo ${line[@]:6:4}
> done < somefile
28 46 5d a2 26 7a 192 168 2 2
00 15 0e c8 a8 a3 192 168 100 3
54 04 2b 08 0c 26 192 168 20 3

Upvotes: 3

SSaikia_JtheRocker
SSaikia_JtheRocker

Reputation: 5063

Please try this too, if it helps (bash version 4.1.7(1)-release)

#!/bin/bash

while read line;do
  arr=($line)

  i=0
  for num in "${arr[@]}";do
     if [ $i -lt 6 ];then
         if [ ${#num} -eq 1 ];then
             arr[i]='0'${arr[i]};
         fi
     fi
     i=$((i+1))

  done
  echo "${arr[*]}"
done<your_file

Upvotes: 0

jaypal singh
jaypal singh

Reputation: 77105

Here is a way with awk if that is an option:

awk '{for(i=1;i<=6;i++) if(length($i)<2) $i=0$i}1' file

Test:

$ cat file
28 46 5d a2 26 7a 192 168 2 2  
0 15 e c8 a8 a3 192 168 100 3
54 4 2b 8 c 26 192 168 20 3

$ awk '{for(i=1;i<=6;i++) if(length($i)<2) $i=0$i}1' file
28 46 5d a2 26 7a 192 168 2 2  
00 15 0e c8 a8 a3 192 168 100 3
54 04 2b 08 0c 26 192 168 20 3

Upvotes: 1

Related Questions