I carry a Leatherman on my belt every day wherever I go. It has become a bit of an extension of my body, which I only really notice when I have to fly somewhere and I’m forced to take it off for the flight. Then I get to my destination and I can’t open the cable ties on my luggage. At the same time, I have a whole pinboard of tools up in my garage, which overlap somewhat with my Leatherman: a dedicated set of pliers, some dedicated screwdrivers and scissors and so on. This is because the is not as good as any of these dedicated tools.
sed -r -i -e 's/ZAR/USD/' -e 's/<DT(.*)>
This does the replacement in-place, is really fast and is quick enough to throw together. This is the kind of thing that sed shines at. In fact, it is exactly what it was designed to do, so it is unsurprising that it does it so well.
import os
import re
from tempfile import mkstemp
filename = "test.txt"
patternStrings = ["ZAR", r"<TD([^>]+)>([0-9]{4})([0-9]{2})([0-9]{2})"]
replacements = ["USD", r"<TD1>243"]
# Compile patterns
patterns = [re.compile(p) for p in patternStrings]
# Create temporary file to hold outputs
_, tempfile = mkstemp()
# Process file
outfile = open(tempfile, 'w')
for line in open(filename):
for pattern, replacement in zip(patterns, replacements):
line = pattern.sub(replacement, line)
outfile.write(line)
outfile.close()
os.rename(tempfile, filename)
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Pattern;
public class Fixer {
static File infile = new File("test.txt");
static String[] patternStrings = {"ZAR", "<TD([^>]*)>([0-9]{4})([0-9]{2})([0-9]{2})"};
static String[] replacementStrings = {"USD", "<TD$1>$2$4$3"};
public static void main(String[] args) throws IOException {
Pattern[] patterns = new Pattern[patternStrings.length];
Scanner in = new Scanner(new FileReader(infile));
// Compile patterns
for (int i=0; i<patternStrings.length; i++) {
patterns[i] = Pattern.compile(patternStrings[i]);
}
// Create temporary file to hold outputs
File tempfile = File.createTempFile("tmp", "tmp");
// Process file
FileWriter outfile = new FileWriter(tempfile);
while (in.hasNextLine()) {
String line = in.nextLine();
for (int i=0; i < patterns.length; i++)
line = patterns[i].matcher(line).replaceAll(replacementStrings[i]);
outfile.write(line + System.getProperty("line.separator"));
}
outfile.close();
// move temp file back to filename
tempfile.renameTo(infile);
}
}
Leave a Reply