简体   繁体   English

有没有办法在sed中获取字符的ASCII码?

[英]Is there a way to get a character's ASCII code in sed?

I'm writing a sed script part of which requires replacing characters from a certain subset with the hexadecimal values of their ASCII codes. 我正在写一个sed脚本,其中一部分需要用其ASCII代码的十六进制值替换特定子集中的字符。 I did some research and I could not find anything, so I'm starting to think that sed does not have a feature that would let me do that. 我做了一些研究,但找不到任何东西,所以我开始认为sed不具备让我做到这一点的功能。 If there are any sed gurus here, could you please enlighten me? 如果这里有sed专家,请您给我启示?

PS: solutions like sed -e "s/A/41/g" -e "s/B/42/g"... etc won't do. PS:诸如sed -e "s/A/41/g" -e "s/B/42/g"... etc将无法执行。

If perl is a viable alternative to you, then: 如果perl可以替代您,那么:

fge@erwin ~ $ perl -pe 's,[abcRte], ord($&) ,ge'
oiiiiisdfa
oiiiiisdf97
abcRte
97989982116101

while IFS= read -r -n1 c; 而IFS =读取-r -n1 c; do printf '%x' "'$c"; 做printf'%x'“'$ c”; done < infile > outfile 完成<infile> outfile

No, sed 's 's' command can only convert characters to their lower/upper case counterparts, it doesn't have a facility to replace them with their equivalent ascii code. 不, sed的s命令只能将字符转换为小写/大写字母,它没有用等价的ascii代码替换字符的功能。 There is the 'y' command for transliteration but that requires a 1-for-1 mapping in length, so that won't work. 有用于音译的“ y”命令,但是它需要1对1映射的长度,因此该命令不起作用。

Without seeing your code, my best recommendation is a move to awk 不看您的代码,我最好的建议是awk

This might work for you: 这可能对您有用:

ord () { printf '%d' "'$1"; }
hex () { printf '%x' "'$1"; }
export -f ord hex
echo {a..z} | sed '/[f-m]/s//$(ord &)/g;s/.*/echo "&"/' | sh
a b c d e 102 103 104 105 106 107 108 109 n o p q r s t u v w x y z
echo {a..z} | sed '/[f-m]/s//$(hex &)/g;s/.*/echo "&"/' | sh
a b c d e 66 67 68 69 6a 6b 6c 6d n o p q r s t u v w x y z

If you have GNU sed: 如果您有GNU sed:

sed '/[f-m]/s//$(ord &)/g;s/.*/echo "&"/e'

or 要么

sed '/[f-m]/s//$(hex &)/g;s/.*/echo "&"/e'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM