Skip to content

Instantly share code, notes, and snippets.

@chrisliuqq
Created February 2, 2019 14:22
Show Gist options
  • Save chrisliuqq/0c3f0d7cf1efdc0d5c98f93b127cc259 to your computer and use it in GitHub Desktop.
Save chrisliuqq/0c3f0d7cf1efdc0d5c98f93b127cc259 to your computer and use it in GitHub Desktop.
txt merge for novels
#!/usr/local/bin/php
<?php
try {
if (!isset($argv[1])) {
throw new Exception("Missing target path", 1);
}
$targetRoot = realpath(sprintf('%s/%s', getcwd(), $argv[1]));
$readMe = getReadMe($targetRoot);
$globPattern = "$targetRoot/{,*,*/*,*/*/*,*/*/*/*}.txt";
$files = glob($globPattern, GLOB_BRACE);
usort($files, 'textIndexCompare');
$exportPath = $readMe['output'];
foreach($files as $file) {
$header = sprintf("====================\n START:%s\n===================\n\n",pathinfo($file)['filename']);
file_put_contents($exportPath, $header, FILE_APPEND);
file_put_contents($exportPath, file_get_contents($file), FILE_APPEND);
$footer = sprintf("====================\n END:%s\n===================\n\n",pathinfo($file)['filename']);
file_put_contents($exportPath, $footer, FILE_APPEND);
}
}
catch (Exception $e) {
printf("\nError: %s\n\n", $e->getMessage());
exit;
}
function textIndexCompare($a, $b) {
$aIndex = getIndexByFileName($a);
$bIndex = getIndexByFileName($b);
return strcmp($aIndex, $bIndex);
}
function getIndexByFileName($filename) {
preg_match_all('/(\d{4,})_/', $filename, $matches);
if (!isset($matches[1])) {
return '0';
}
$index = implode('', $matches[1]);
return $index;
}
function getReadMe($targetRoot) {
$result = [
'name' => 'unknown'
];
$globPattern = "$targetRoot/{,*,*/*,*/*/*,*/*/*/*}.md";
$files = glob($globPattern, GLOB_BRACE);
if (isset($files[0])) {
$readme = file_get_contents($files[0]);
// dd($readme);
preg_match_all('/title_zh.?: (.*)/', $readme, $matches);
if (isset($matches[1]) && $title = array_pop($matches[1])) {
$result['name'] = trim($title);
}
}
$outputBase = sprintf('%s/out', getcwd());
if (!file_exists($outputBase)) {
mkdir($outputBase, 0644);
}
$result['output'] = sprintf('%s/%s 00 Web.txt', $outputBase, $result['name']);
$exportPath = sprintf('%s/out/', getcwd());
$result['output'] = sprintf('%s/%s 00 Web.txt', $exportPath, $result['name']);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment