filter.py
Download filter.py
1: #!/usr/bin/python3
2: """ Sample generic filter command, written in Python. A "filter"
3: should process each filename argument, or stdin if no arguments
4: are given. A "-" for a filename means stdin.
5:
6: This script prints a header line, then the file's contents,
7: and then a footer line. Any line containing a plus symbol
8: is converted to uppercase, just for laughs.
9:
10: Written 4/2014 by Wayne Pollock, Tampa Florida USA
11: """
12:
13: import re, sys
14:
15: def main ():
16: # Check if any command-line args were given;
17: # if not, use "-" (Standard Input):
18: if len( sys.argv[1:] ) == 0:
19: sys.argv.insert( 1, '-' )
20:
21: # Process each filename on the command line:
22: for filename in sys.argv[1:]:
23: process( filename )
24: print() # Print a blank line, as a separator.
25:
26: # Do something interesting for a given file:
27: def process ( filename ):
28:
29: # If the argument is "-", use Standard Input instead:
30: if filename == '-':
31: filename = "STDIN" # A more useful name than "-".
32: file = sys.stdin
33: else:
34: file = open( filename )
35:
36: # This part is done once per file:
37: print ( F"""
38: file prolog: filename: {filename}
39: """ )
40:
41: # This is done for each line in the file:
42: for line in file:
43: if re.search( "\+", line ): # find lines containing a "+"
44: line = line.upper()
45: print( line, end="" )
46:
47: # This part is done once per file:
48: print( "\n\tfile epilogue: The end" )
49:
50: # Close the file, except if standard input; otherwise,
51: # a second "-" as a command line arg will fail:
52: if file != sys.stdin:
53: file.close()
54:
55: # This standard line allows this file to be imported or run directly:
56: if __name__ == "__main__": main()