I build ord
and chr
functions and they work just fine.
But if I take a file that contains \n
, for example:
hello
CHECK THIS HIT
YES
when I ord
everything I don't get any new line values. Why is that? I'm writing in Bash.
Here is the code that I am using:
function ord {
ordr="`printf "%d\n" \'$1`"
}
TEXT="`cat $1`"
for (( i=0; i<${#TEXT}; i++ ))
do
ord "${TEXT:$i:1}"
echo "$ordr"
done
Your
ord
function is really weird. Maybe it would be better to write it as:Then you would use it as:
This still leaves two problems: you won't be able to have null bytes and you won't see trailing newlines. For example (I called your script
banana
andchmod +x banana
):Two problems show here: the null byte is removed from Bash in the
TEXT=$(cat "$1")
part, as a Bash variable can't contain null bytes. Moreover, this step also trims trailing newlines.A more robust approach would be to use
read
:With this modification:
Note that this script will depend on your locale. With my locale (
LANG="en_US.UTF-8
):whereas:
That's to show you that Bash doesn't read bytes, but characters. So depending on how you want Bash to treat your data, set
LANG
accordingly.If your script only does that, it's much simpler to not use an
ord
function at all:It's that simple!