3

I'm looking for an alias to convert hex from hexdump output into "Python's" hex notation:

$ echo "5f 74 34 0c c9 7b 9f f8  7a 7c 46 ff ff 5c 31 26" | sed 's/  */\\x/g' | awk '{print "\\x"$0}'
\x5f\x74\x34\x0c\xc9\x7b\x9f\xf8\x7a\x7c\x46\xff\xff\x5c\x31\x26

The above works so I tried creating an alias in my .bashrc as such:

alias pythonhex="sed 's/  */\\x/g' | awk '{print \"\\\\x\"$0}'"

But it doesn't seem to work:

$ echo "5f 74 34 0c c9 7b 9f f8  7a 7c 46 ff ff 5c 31 26" | pythonhex 
\x

It appears in this case that sed isn't getting anything from STDIN, and awk is just prepending \x to nothing.

  • 2
    I think the problem is you're using double quotes as the outer quotes, which means that $0 is getting interpreted at the time the alias is created. – criswell Aug 20 '15 at 12:34
3

This is a quoting issue. Use single quotes to prevent $0 from expansion, and properly escape each literal single quote:

alias pythonhex='sed '\''s/  */\\x/g'\'' | awk '\''{print "\\x"$0}'\'
  • You are correct, quoting is a real problem with the alias command interface. The problem is that you need to pass the shell parser with the alias definition. UNOS (the first UNIX clone) had a method to bypass the parser for alias definitions that thus could be entered in raw form. I recently decided to add this trick to the Bourne Shell. If you are interested, have a look into the Bourne Shell man page and check the section for #-commands: schillix.sourceforge.net/man/man1/bosh.1.html – schily Aug 20 '15 at 21:20
1

It is true that your alias problem was a quoting issue, resolved correctly by the user choroba.

But you may consider a simpler function:

pythonhex(){ printf "\134x%s" "$@"; echo; }

Used as:

$ pythonhex 5f 74 34 0c c9 7b 9f f8  7a 7c 46 ff ff 5c 31 26
\x5f\x74\x34\x0c\xc9\x7b\x9f\xf8\x7a\x7c\x46\xff\xff\x5c\x31\x26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.