[英]How to turn a string into a modified hex representation?
i want to turn a string like我想把一个字符串像
AaAa
into进入
a string like this像这样的字符串
%<41>%<61>%<41>%<61>
Simple enough with the programming languages i am familar with, but with bash i can't get get the piping right to do what i am trying to do:使用我熟悉的编程语言足够简单,但是使用 bash 我无法正确执行我想要做的事情:
%<FF>
%<FF>
this is my current way which gets me half way there:这是我目前的方式,让我走到了一半:
echo -n "AaAa" | od -A n -t x1
If you are already using od
,如果您已经在使用
od
,
printf "%%<%s>" $(od -A n -t x1<<<"AaAa")
For an all-bash without od
,对于没有
od
的全bash,
while read -r -N 1 c; do printf "%%<%02X>" "$( printf "%d" \'$c )"; done <<< AaAa
The downside of this approach is that it spawns a subshell for every character, and assumes ASCII/UTF8.这种方法的缺点是它为每个字符生成一个子外壳,并假定为 ASCII/UTF8。
@Shawn pointed out that you don't need the subshell - @Shawn 指出您不需要子外壳 -
while read -r -N 1 c; do printf "%%<%02X>" \'$c; done <<< AaAa
I noticed that these are leaving the string terminator in your output, though, and realized I could eliminate that and the read
by assigning the data to a variable and using the built-in parsing tools.不过,我注意到这些将字符串终止符留在您的输出中,并意识到我可以通过将数据分配给变量并使用内置解析工具来消除它和
read
。
$: x=AaAa && for((i=0;i<${#x};i++)); do printf "%%<%02X>" \'${x:i:1}; done; echo
%<41>%<61>%<41>%<61>
A simple Perl substitution would do the trick:一个简单的 Perl 替换就可以解决问题:
echo -n AaAa | perl -pe's/(.)/ sprintf "%%<%02X>", ord($1) /seg'
Shorter:更短:
echo -n AaAa | perl -ne'printf "%%<%02X>", $_ for unpack "C*"'
In both cases, the output is the expected在这两种情况下,输出都是预期的
%<41>%<61>%<41>%<61>
(No trailing line feed added. If you want one, append ; END { print "\\n" }
.) (没有添加尾随换行。如果你想要一个,附加
; END { print "\\n" }
。)
您可以通过管道传输到sed
以将每个字节包装在%<>
,然后删除空格。
echo -n "AaAa" | od -A n -t x1 | sed -E -e 's/[a-z0-9]+/%<&>/g' -e 's/ //g'
Maybe awk
也许
awk
echo -n "AaAa" |
od -A n -t x1 |
awk 'BEGIN { ORS = "" } { for (i = 1; i <= NF; i+=1) print "%<"$i">"}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.