简体   繁体   中英

Create txt file listing files in subfolders

I have a directory that contains thousands of subfolders. I want to make it auto create a text file in each subfolder that will list all the files in that subfolder. I am running on Ubuntu 10.04 How can I do this in javascript or php?

In shell, it's a single command (albeit one that embeds other commands):

find /start/path -type d -exec sh -c "ls {} > {}/files.txt" \;

If you really need this in another language, please clarify your requirements.

This is not a JOB for php .. for Experimental Purpose you can use this :

$di = new RecursiveIteratorIterator(new RecursiveDirectoryIterator(__DIR__, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
foreach ( $di as $file ) {
    $name = $file->getPathInfo() . "/files.txt";
    touch($name);
    file_put_contents($name, $file->getFilename() . PHP_EOL, FILE_APPEND);
}

If you want to remove the text file you can always run

foreach ( $di as $file ) {
    $name = $file->getPathInfo() . "/files.txt";
    is_file($name) AND unlink($name);
}

Its a sample php code which will create a file "files.txt" inside each directory and will put all the filenames in that folder ( will not add folder names).. Make sure you have write permission to all the folders

function recursive($directory)
{
    $dirs = array_diff(scandir($directory), Array( ".", ".." ));
    $dir_array = array();

    foreach($dirs as $d)
    {
        if(is_dir($directory."/".$d)){
            $dir_array[$d] = recursive($directory."/".$d);
        }
        else{
            $dir_array[$d] = $d;
            $fp = fopen("$directory/files.txt","a");
            fwrite($fp,"\n$d");
        }
    }
}   

recursive($start_directory);
?>

You can achieve this by writing recursive PHP function using scandir. For more help on PHP scandir, check this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM