取前 16 个字符并将其转换为十六进制字符串

Take first 16 character and covert it into hex string

我有 UUID,3abbea88-c77d-11eb-b8bc-0242ac130003,我想获取此字符串的前 16 个字符,并使用 shell 脚本获取前 16 个字符的十六进制字符串。

我试过了,

code=$(echo -n ${${ID##*:}:0:16} | od -A n -t x1)
HEX_ID=$(echo ${code//[[:blank:]]/})

有更好的方法吗?

预期输出:33616262656138382d633737642d3131

Perl 来拯救!

perl -le 'print unpack "H32", shift' 3abbea88-c77d-11eb-b8bc-0242ac130003
  • -l 添加换行符到 print
  • unpack 获取一个字符串并将其扩展为基于模板的值列表。 H32 表示“获取字符并将其解释为 32 个十六进制值”。
  • shift 读取第一个命令行参数。

或者,使用 xxdhead

echo 3abbea88-c77d-11eb-b8bc-0242ac130003 | xxd -p | head -c32

那肯定是 useless echo.

可能avoid uppercase for your private variables.

uuid='3abbea88-c77d-11eb-b8bc-0242ac130003'
tmp=${uuid//-/}
hex_id=$(od -A n -t x1 <<<${tmp:0:13})
hex_id=${hex_id//[[:blank:]]/}
hex_id=${hex_id%0a}

这里的字符串没有吸引力地向 od 提供尾随换行符,我们必须 trim 关闭它。

使用 od,您可以使用 -N 选项简单地限制读取的字符数:

HEX_ID=$(od -A n -t x1 -N 16 <<< ${ID##*:} | tr -dc '[:xdigit:]')

编辑:tr 用于抑制非十六进制字符,即空格和潜在的换行符。

Bash-仅:

 while read -r -N 1 c                      # read input string 1 char at a time
 do [[ "$c" == " " ]] ||                   # skip embedded spaces
     printf "%02X" "$(                     # output the hexidecimal value of 
       printf "%d" \'$c                    # the ASCII decimal ordinal of $c
     )" 
 done <<< "${text##*:}"                    # ignoring the leading trash to the :
 echo                                      # newline-teminate the output

全部在一行中:

 while read -rn1 c;do [[ "$c" == " " ]]||printf %02X $(printf "%d" \'$c);done<<<"${text##*:}";echo

这不是最快的方法...

hexdump 搞定一切:

hexdump -n 16 -ve '1/1 "%.2x"'

-n 16表示只处理前16个字节
-e '1/1 "%.2x"' 表示使用给定的 printf 格式显示每个字节
-v 表示正常显示(没有这个,它用 * 替换欺骗部分)


echo '3abbea88-c77d-11eb-b8bc-0242ac130003' | hexdump -n 16 -ve '1/1 "%.2x"'

输出:

33616262656138382d633737642d3131