Skip to content

Instantly share code, notes, and snippets.

@mdPlusPlus
Last active December 11, 2020 09:32
Show Gist options
  • Save mdPlusPlus/bd95dcf2c2fa5c173f8702a6df6fd4f9 to your computer and use it in GitHub Desktop.
Save mdPlusPlus/bd95dcf2c2fa5c173f8702a6df6fd4f9 to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import org.apache.commons.io.FileUtils;
import static java.lang.System.exit;
public class HashReplace {
public static void main(String[] args) {
//args[0] hashes (format hash:plaintext)
//args[1...] file(s) to replace in
if(args.length < 2) {
System.err.println("not enough parameters");
exit(1);
}
File hashes = new File(args[0]);
File[] textFiles = new File[args.length-1];
for (int i = 0; i<args.length; i++) {
File f = new File(args[i]);
if (!f.exists()) {
System.err.println("file " + args[i] + " does not exist");
System.exit(1);
}
if (i > 0) {
textFiles[i-1] = f;
}
}
HashMap<String,String> hashMap = new HashMap<>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(hashes.toString()), "UTF-8"));
String s;
while ((s = in.readLine()) != null) {
String hash = s.substring(0, s.indexOf(":")).toLowerCase();
String plaintext = s.substring(s.indexOf(":")+1);
System.out.println("reading " + hash + " <-> " + plaintext);
hashMap.put(hash, plaintext);
}
} catch (UnsupportedEncodingException e) {
//won't happen
} catch (IOException e) {
//shouldn't happen
}
for (File f : textFiles) {
System.out.println("replacing in file " + f.toString());
try {
String content = FileUtils.readFileToString(f, "UTF-8");
for (Map.Entry<String,String> entry : hashMap.entrySet()) {
content = content.replaceAll("(?i)" + Matcher.quoteReplacement(entry.getKey()), Matcher.quoteReplacement(entry.getValue()));
}
FileUtils.writeStringToFile(f, content, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("finished");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment