bashsed

How to replace all chars of a string by theirs ASCII code in bash using sed?


I have this code but it does not work :

w(){ 
  echo $(printf "%d" "'$1")
}
echo $(w "a")
t="abcd"
echo "$t" | sed "s/./(w &)/g"
echo "$t" | sed "s/./$(w &)/g"

I get :

97
(w a)(w b)(w c)(w d) 
0000

I want

979899100

I tried putting ' or " around w or $(w &), as advised by the documentation, nothing works.

What did I miss ?

EDIT

keeping on my searches, I found this

export -f w

I tried but I'm facing new problems, and I found nothing explaning them on the web.

First code:

function w(){
echo $(printf "%d" "'$1")
}
export -f w
t="abcd"
echo $t | sed 's/./w &/eg' 

I get

97

The option 'g' doesn't work. Why ?

Second code :

function w(){
echo $(printf "%d" "'$1")
}
export -f w
t="abcd"
echo $t | sed 's/./$(w &)/eg' 

Now I get :

/bin/sh: 979899100: command not found

I don't understand why with the second code I get "command not found", and not with the first. Because I ask for evaluation with $(..) ?

P.S. May be I should create a new question ?


Solution

  • This might work for you (GNU sed):

    sed 's/./ \\"\\&/g;s/.*/printf "%d"&/e' file
    

    Convert each character into the form printf accepts.

    Then prepend the printf and its first parameter and evaluate each line in turn.