Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I print the numerical ASCII values of each character in a text file. Like cat, but showing the ASCII values only... (hex or decimal is fine).

Example output for a file containing the word Apple (with a line feed) might look like:

065 112 112 108 101 013 004
share|improve this question
up vote 9 down vote accepted

The standard command for that is od, for octal dump (though with options, you can change from octal to decimal or hexadecimal...):

$ echo Apple | od -An -vtu1
  65 112 112 108 101  10

Note that it outputs the byte value of every byte in the file. It has nothing to do with ASCII or any other character set.

If the file contains a A in a given character set, and you would like to see 65, because that's the byte used for A in ASCII, then you would need to do:

< file iconv -f that-charset -t ascii | od -An -vtu1

To first convert that file to ascii and then dump the corresponding byte values. For instance Apple<LF> in EBCDIC-UK would be 193 151 151 147 133 37 (301 227 227 223 205 045 in octal).

$ printf '\301\227\227\223\205\045' | iconv -f ebcdic-uk -t ascii | od -An -vtu1
  65 112 112 108 101  10
share|improve this answer

hexdump, od, xxd, or $YOUR_FAVORITE_LANGUAGE can all do that.

% echo Apple | hexdump -C
00000000  41 70 70 6c 65 0a                                 |Apple.|
00000006
% echo Apple | perl -ne 'printf "%vd\n", $_' 
65.112.112.108.101.10
% echo Apple | clisp <( echo '(print (mapcar #'\''char-code (coerce (read-line *standard-input*) '\''list)))' )
(65 112 112 108 101)
% 
share|improve this answer
    
Excellent answer, thankyou. Especially hexdump -C. Awarded to Stephane simply because his answer also resolved, and he was first (by just a hair), but both are excellent. – Mtl Dev Mar 8 at 22:45
    
Yet another command: python -c "print open('file', 'rb').read().encode('hex')" – J.F. Sebastian Mar 9 at 3:03
    
@J.F.Sebastian Better echo 'Apple' | python -c "import sys;print sys.stdin.read().encode('hex')" – heemayl Mar 9 at 3:39
    
@heemayl : wrong. It may corrupt a binary file on Windows – J.F. Sebastian Mar 9 at 3:41
    
@heemayl stdin uses the text mode by default that may translate newlines (os.linesep -> '\n') – J.F. Sebastian Mar 9 at 3:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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