cat
concatenates files given as arguments on command line to standard output, it reads bytes at a time an as default does not perform any interpretation of the bytes it reads.
In your first example you are redirecting stdout to a file, that's why you get a new file.
In your second example the bytes are written to the terminal, and it is the terminal which is interpreting sequences of characters as control sequences for the terminal, this is why you get unusual behaviour on your terminal. It has nothing to do with cat
as such, cat
doesn't know what you are going to do with it's output. You might be sending it through a pipe to another program to interpret/process/print or play "Singing in the rain".
So following the unix philosophy,
do one thing, do one thing only, but do it well
cat
should not attempt to second guess what you are trying to do.
edit 1 reply to @kiwy's 1st comment below.
Yes and No, let me explain,
No, if you cat
to a terminal, because it (the terminal software) is sending the output to your screen or interpreting control sequences (it is emulating an old piece of hardware ie. a teletype device).
but,
Yes if you cat to a pipe and the program recieving can interpret the characters as commands.
look cat this for an example, cat anyOldShellScript | bash
bash will interpret what it gets as commands.
You can do this using printf
and bash
:
printf '%08x\n' $(< test.txt)
Or using printf and bc...just...because?
printf '%08s\n' $(bc <<<"obase=16; $(< test.txt)")
In order to print the output to a text file just use the shell redirect >
like:
printf '%08x\n' $(< test.txt) > output.txt
Best Answer
The standard command for that is
od
, for octal dump (though with options, you can change from octal to decimal or hexadecimal...):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:
To first convert that file to ascii and then dump the corresponding byte values. For instance
Apple<LF>
in EBCDIC-UK would be193 151 151 147 133 37
(301 227 227 223 205 045
in octal).