Created
February 2, 2019 14:22
-
-
Save chrisliuqq/0c3f0d7cf1efdc0d5c98f93b127cc259 to your computer and use it in GitHub Desktop.
txt merge for novels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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