Super User is a question and answer site for computer enthusiasts and power users. 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



I'm looking to obtain


Or, this would also be helpful: given:


I'm looking to obtain

!   34-2=5

Where! Is some indication that inequality or equality is false. I'm looking for something that processes text files.

share|improve this question
In the second case, it would be real easy if the equality lines used double equals signs, such as "34-2==5" instead of just a single, since a single equals sign is used for assignment in most programming languages. – Daniel Andersson May 11 '12 at 15:17
I can change the signs to anything, so where it's =, I could put ==. – e a005 May 11 '12 at 15:18
Also, I assumed a *nix environment since you asked about that in a separate question very recently, but it would be good if you could clarify if you want a *nix solution specifically, or some other platform or the most general solution (Perl is quite general, but for other people answering it could be good to know). – Daniel Andersson May 11 '12 at 15:48
up vote 1 down vote accepted

First case

perl -nle 'print $_."=".eval($_)' filewithexpressions
  • -n loops over the lines.
  • -l strips newlines from $_, but separates output lines with newlines for you.
  • -e defines an expression to be run.
  • $_ is a placeholder for "current line".
  • . concatenates strings.
  • eval() will take a string and evaluate it as code, so e.g. eval('5+8') returns 13.

Second case

With dual equals signs in the infile as noted in my comment to the original question:

perl -ne 'print eval($_)?" ":"!",$_' filewithequalities

As before in general.

  • -l is not needed/wanted since the newlines take care of themselves in this case.
  • The ?: construct is a ternary operator. If the preceding expression is true, return a blank space, otherwise return an exclamation mark.
share|improve this answer
Good answer, complete and with an explanation. – e a005 May 11 '12 at 20:40

Here's a python script to handle the first part of your question:

import sys
for line in sys.stdin:
    print "%s=%s" % (line.rstrip(), eval(line))

Put the above code in, put the input in test.dat, and run like so:

python < test.txt

I'm assuming a unix-like OS. Note that it can be dangerous to pass input to any script that runs eval---don't pass unknown data to this script.

share|improve this answer

Your Answer


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.