Mar-07-2020, 07:26 PM
sub.py is my "sub" command. it substitutes one string (arg 2) for another (arg 1) in one or more files or in th stdin/stdout stream for file name "-" (or if no names given).
#!/usr/bin/env python3 from os import rename,remove from os.path import exists from subprocess import run from sys import argv,stderr,stdin,stdout from time import time as secs dne = 0 abort = False if len(argv)<3: exit('string substition needs old string in arg 1 and new string in arg2 followed by an optional list of file names.') exe = argv.pop(0) old = argv.pop(0) new = argv.pop(0) fns = argv if argv else ['-'] for fn in fns: if fns.count(fn)>1: exit('duplicate file name: '+repr(fn)) if fn!='-': if not exists(fn): print('file does not exist: '+repr(fn),file=stderr) dne += 1 if dne: exit('aborting due to '+str(dne)+' missing file'+'s'[dne==1:]) for fn in fns: if fn=='-': tn = None fi,fo = stdin,stdout else: tn = fn+'+'+str(int(secs()*3906250)) fi = open(fn,'r') fo = open(tn,'w') changed = 0 for ol in fi: nl = ol.replace(old,new) if nl!=ol: changed += 1 fo.write(nl) fi.close() fo.close() if changed and fn!='-': run(['chmod','--quiet','--reference='+fn,tn]) run(['chown','--quiet','--reference='+fn,tn]) rename(fn,fn+'~') rename(tn,fn) else: if tn: remove(tn)
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.