Skip to content

Instantly share code, notes, and snippets.

@RobertWang
Created April 22, 2014 09:07
Show Gist options
  • Save RobertWang/11171157 to your computer and use it in GitHub Desktop.
Save RobertWang/11171157 to your computer and use it in GitHub Desktop.
dos2unix
<?php
/**
* dos2unix
* @author Robert <[email protected]>
*/
// 待处理的目录
$work_dir = getcwd();
$opts = array(
// sub 配置是否遍历子目录 true 为递归遍历
'sub' => true,
// filter 配置需要转换的文件扩展名
'filter' => array('js','php','html','txt'),
);
$_timer_start = microtime(true);
$result = walk_dir($work_dir);
$_timer_end = microtime(true);
$_timer_cost = $_timer_end - $_timer_start;
// print_r($result);
echo 'convert done!', PHP_EOL, ' ==== summary ====', PHP_EOL;
echo 'dir path scaned ', $result['dirs'], ', file scaned ', $result['files'], PHP_EOL;
echo $result['converted'], ' total converted files!!!', PHP_EOL;
echo 'total used ', $_timer_cost, 'micro-seconds. ', PHP_EOL;
function walk_dir ( $workdir, $opts = array() ) {
if ( !is_dir($workdir) ) {
echo $workdir, ' is not a dir name ', PHP_EOL;
exit;
}
static $_workdir;
if ( trim($_workdir)!='' ) $_workdir = $workdir;
$opts['sub'] = ( isset($opts['sub']) ) ? !!$opts['sub'] : true;
$opts['filter'] = isset($opts['filters']) ? $opts['filters'] : array('js', 'php', 'html', 'txt');
static $_sc_dir = 0, $_sc_file = 0, $_sc_converted = 0;
chdir($workdir);
$list = glob('*');
$_sc_dir ++ ;
//echo 'Debug Info : current path : == ', $workdir, PHP_EOL;
foreach ( $list as $i => $item ) {
$_item = $workdir.DIRECTORY_SEPARATOR.$item;
if ( is_dir($_item) ) {
walk_dir ( $_item );
}
if ( is_file($_item) ) {
//echo 'File => ', $item, PHP_EOL;
$_sc_file ++ ;
$_exttype = pathinfo($_item, PATHINFO_EXTENSION);
if ( in_array($_exttype, $opts['filter']) ) {
convert_dos2unix($_item);
$_sc_converted ++ ;
}
}
}
return array('status'=>true, 'dirs'=>$_sc_dir, 'files'=>$_sc_file, 'converted'=>$_sc_converted);
}
function convert_dos2unix( $oldfile, $newfile='' ) {
if ( !is_file($oldfile) ) {
echo $oldfile, ' is not a file or not exists!', PHP_EOL;
return false;
}
if ( $newfile == '' ) {
$newfile = $oldfile;
}
$_content = file_get_contents($oldfile);
$_dos_return = "\r\n";
$_unix_return = "\n";
$_content = str_replace($_dos_return, $_unix_return, $_content);
file_put_contents($newfile, $_content);
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment