help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Reading and handling "control" characters from a file


From: Conrad J. Sabatier
Subject: Re: [Help-bash] Reading and handling "control" characters from a file
Date: Sat, 21 Apr 2012 22:26:49 -0500

On Sat, 21 Apr 2012 19:39:10 -0500
"Conrad J. Sabatier" <address@hidden> wrote:

> On Sun, 22 Apr 2012 01:56:46 +0200
> Davide Brini <address@hidden> wrote:
> 
> > On Sun, 22 Apr 2012 01:48:49 +0200, Davide Brini <address@hidden>
> > wrote:
> > 
> > > > > Shouldn't the single quote trick work here? eg
> > > > > 
> > > > > $ a=$(printf '\x4\n')
> > > > > $ printf "%d\n" "'$a"
> > > > > 4
> > > > > 
> > > > 
> > > > Yes, I thought that was the solution for a brief time, but it
> > > > still fails when the character is a newline, for some odd
> > > > reason.  Bash seems to be rather fickle when it comes to certain
> > > > things, allowing this, objecting to that.
> > > 
> > > You must be doing something odd, because newline works for me:
> > > 
> > > $ a=$'\n'
> > > $ printf "%d\n" "'$a"
> > > 10
> > > $ printf -v byte "%d" \'"$a"
> > > $ echo "$byte"
> > > 10
> > > 
> > > Check how you're handling whatever you think should contain the
> > > newline before converting it.
> > 
> > Maybe I see, you're using "read" to get the values. In that case,
> > use the -d '' option to read so bash will only stop at NULs and
> > newlines will be read just like any other character.
> 
> Eureka!  That's it!  It works!  How did I overlook that?
> 
> Thank you so much!  End of the mystery!

Just a quick summary here.

I'm now using the following for all file reads:

read -d '' -r -N 1      #(the argument to the -N option may vary)

I discovered that -N works more reliably than -n.  I was still getting
some stray bogosity on certain inputs using -n, which disappeared as
soon as I switched to -N instead.

Then, if the byte just read is raw numeric (not text) data:

printf -v byte "%d" \'"${REPLY}"

And then "${byte}" can be used for whatever purpose is needed.

Otherwise, no conversion is necessary, and "${REPLY}" can simply be
used "as is" or, of course, copied directly to some other variable.

Amazing how simple some things turn out to be, once you know how.  :-)

Thanks for the help, folks!  No telling how long it might have taken me
to get to this on my own.  :-)

-- 
Conrad J. Sabatier
address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]