简体   繁体   中英

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. 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. If there are any sed gurus here, could you please enlighten me?

PS: solutions like sed -e "s/A/41/g" -e "s/B/42/g"... etc won't do.

If perl is a viable alternative to you, then:

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

while IFS= read -r -n1 c; do printf '%x' "'$c"; done < 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. There is the 'y' command for transliteration but that requires a 1-for-1 mapping in length, so that won't work.

Without seeing your code, my best recommendation is a move to 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:

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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