user500944
user500944

Reputation:

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?

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

Upvotes: 1

Views: 1153

Answers (3)

potong
potong

Reputation: 58440

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'

Upvotes: 0

fge
fge

Reputation: 121750

If perl is a viable alternative to you, then:

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

Upvotes: 1

SiegeX
SiegeX

Reputation: 140377

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

Upvotes: 0

Related Questions