2

If I look for a filename pattern in perl, you can do this simple:

ls -l | perl -n -e'if(/.*180205.*/){ print "$_\n"; }'

-n
causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed -n or awk:

LINE:
  while (<>) {
      ...             # your program goes here
  }

How can I code this in python3? (python3 --help shows not such option)

Gerd
  • 2,265
  • 1
  • 27
  • 46

1 Answers1

3

Python oneliners with python -c '...' are extremely restricted, as the Python grammar assumes that each statement sits on its own line. You can combine some statements with a semicolon “;”, but some statements need to have their own line, notably compound statements like loops. If you want to write this on the command line, we have to express the loop over all lines as a list comprehension:

python3 -c 'import re, fileinput; [print(line, end="") for line in fileinput.input() if re.search("180205", line)]'

This is of course fairly unreadable, because Python is not well-suited for one-liners. Looping over the fileinput.input() is similar to Perl's -n option.

If you want to use Python, consider writing a script. This is much more readable:

import re, fileinput
for line in fileinput.input():
    if re.search("180205", line):
        print(line, end="")
amon
  • 57,091
  • 2
  • 89
  • 149