0

I am attempting the perl to python transition and I also happen to use lots of perl one-liners in the bash prompt for parsing files. For example,

cat input_file.txt|perl -ne 'chomp $_; @a=split /\t/,$_;print "$_\n" if ($a[3]>=50)' > output_file.txt

loops through through the file and prints only those lines that have the 4th column with a value greater than 50. This is accomplished with the "perl -ne" flag.

My question: Does python have an equivalent to "perl -ne" or have any other flags beyond "python -c" for taking commands from the prompt? Most solutions I have seen for using python commands from the prompt are ugly and would be solved with the use of such switches.

If not, I'll just have to use perl for on the fly one liners and python for scripting

Thanks!

Josh
  • 1,005
  • 1
  • 11
  • 18
  • Related: [Python equivalent to perl -pe?](http://stackoverflow.com/q/7842919/176646) (`-p` is similar to `-n`, but prints each line automatically) – ThisSuitIsBlackNot Apr 21 '15 at 15:23
  • 1
    If you're looking for a "cleaner" language, but all the one-liner goodies, investigate Ruby. – glenn jackman Apr 21 '15 at 15:23
  • 1
    +1 to glenn jackman's comment. Python is not a good one-liner language due to its dependence on indentation as a core of its syntax. – Jake Griffin Apr 21 '15 at 15:25
  • very easy create a script that takes args with python and just run the script – Padraic Cunningham Apr 21 '15 at 15:30
  • @Jake Griffin, meh, I rarely put my Perl "one-liners" all on one line. There's no reason for the code to be unreadable. – ikegami Apr 21 '15 at 16:15
  • @ikegami, I was referring to the example given in the question (piping output from one command to another). That is not possible to do in one line in python without it looking significantly more complex. – Jake Griffin Apr 21 '15 at 16:18
  • @Jake Griffin, And I said, so what? I wouldn't even have put all that Perl code on one line. Don't put it all on one line. `sh` strings can contain newlines. – ikegami Apr 21 '15 at 16:42
  • (Then again, I would have used `perl -F'\t' -lane'print if $F[3] >= 50'`) – ikegami Apr 21 '15 at 16:45
  • @ikegami: Fair enough, however, I don't think that the example given could be done as succinctly as perl or ruby. I will say however that I favor the readability of python. It just doesn't lend itself well to the example the asker gave. – Jake Griffin Apr 21 '15 at 16:45
  • @JakeGriffin: I agree wholeheartedly – Borodin Apr 21 '15 at 18:51
  • @PadraicCunningham: yes, but it took me 45 seconds to write it as a pipe and it would take a few minutes to write/save a script. I'm disappointed python doesn't have these switches. What it means is that while perl has the power of sed and awk from the command line, python does not seem to. – Josh Apr 22 '15 at 16:05

0 Answers0