I'm always learning something
new.
For years I've used the
bc command in interactive
mode. bc stands for
basic calculator.
Here's a nice blog post that
introduces bc:
Unix Basic Calculator
Interactive mode is fine. That's
where you sit there and type things
like this:
1 + 1 + 1
After you hit enter, you
get this answer back:
3
That's great if you are doing
a simple calculation. But what
about lots and lots of numbers.
How do you deal with this?
This morning, I was working with
the vim editor. I was pulling
some numbers out of a web page. I
wanted to add all these numbers
together like this:
24 + 7 + 9 + 27
It was a lot more numbers then
I'm showing you here. There were
about 52 numbers embedded in a web
page that I wanted to add together.
That's way too many numbers to add
together interactively. What if I
made a typo?
Also, why should I have to type the
numbers at all. That's what vim
is for, right? In this case, I used vim
to format the numbers for me and then
put plus signs (+) in between each number.
After I was finished editing the web page
with vim, I was left with a single line
that consisted of nothing but numbers separated
by plus signs (+).
Vim is my all-time favorite programmer's
editor:
My Favorite vim Commands
With vim, I used regular expressions
and vim commands to pare my saved
web page down to just 52 numbers on one line
with a plus sign (+) separating each number.
The next step? I was wondering about that.
I figured there must be a way to use bc
in batch mode. By batch mode, I mean
a way to get bc to run a bunch of commands
that are stored in a text file.
Turns out there is a way. I discovered
it when I read the bc man page. It's
simple. Just put the math operations in
a text file and feed these numbers to bc.
Here's what I typed:
bc <numbers.txt
It worked like a charm! My 52 numbers
were all added together. This is a very
powerful feature that I'm sure I'll be
making great use of in the future.
The simplicity of this approach is that
you feed your batch file into bc
via standard input and you get your
answer on standard output. In other
words, a Unix filter.
Here's the input and output together:
bc <numbers.txt 256
I love Linix for this reason. So many
primitive commands that you can do such
great things with. Linix is a great time-saver.
Ed Abbott
No comments:
Post a Comment