Solved

Combine all files in one txt

Posted on 2016-09-06
9
45 Views
Last Modified: 2016-09-07
How do I combine all my files named "389476_845786y.edi_5" (Random numbers but the beginning 3 and the _# at the end is stable, using php code, in a document called "combined.txt"
0
Comment
Question by:Jasmine Ikhreishi
  • 4
  • 3
  • 2
9 Comments
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41786082
Read the files with file_get_contents() or file().  The file contents will be strings or arrays.  Append the files to one another.  If using arrays, you can use implode() to rebuild the strings.  Write the resulting strings with file_put_contents().
1
 
LVL 1

Author Comment

by:Jasmine Ikhreishi
ID: 41786101
so i do
implode $myfiles =>'combined.txt' ?
0
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41786134
Try this  - change wild card to match input files and $output path.
<?php
$output = 'combined.txt';
$files = glob("*.edi_5");

foreach($files as $f) {
    file_put_contents($output, file_get_contents($f), FILE_APPEND);
}

Open in new window

0
Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

 
LVL 109

Accepted Solution

by:
Ray Paseur earned 250 total points
ID: 41786135
This should help you get started.
<?php // demo/temp_jasmine_5.php
/**
 * https://www.experts-exchange.com/questions/28967933/Combine-all-files-in-one-txt.html
 * Generate some files named like "389476_845786y.edi_5"
 */
error_reporting(E_ALL);
echo '<pre>';


// GENERATE THE TEST FILES
$names =
[ "389_ABC.edi_5"
, "389_DEF.edi_5"
, "389_GHI.edi_5"
]
;
$alpha = str_split('ABCDEFG');
foreach ($names as $name)
{
    shuffle($alpha);
    $string = implode(NULL, $alpha) . $name;
    file_put_contents('storage' . DIRECTORY_SEPARATOR . $name, $string);
}


// SHOW HOW TO COMBINE THEM
$iterator = new FilesystemIterator('storage', FilesystemIterator::SKIP_DOTS + FilesystemIterator::CURRENT_AS_PATHNAME);

// USE A REGULAR EXPRESSION TO MATCH THE DESIRED FILE NAMES
$regex
= '#'          // REGEX DELIMITER
. DIRECTORY_SEPARATOR
. '389'        // STRING LITERAL "the beginning 3"
. '.*?'        // ANYTHING OR NOTHING
. 'edi_'       // STRING LITERAL
. '[\d]'       // CHARACTER CLASS FOR DIGITS
. '{1}'        // EXACTLY ONE DIGIT
. '$'          // AT THE END OF THE STRING
. '#'          // REGEX DELIMITER
;

// GATHER THE LIST OF THE DESIRABLE FILES
$desirable = [];
foreach ($iterator as $key => $filepath)
{
    if (preg_match($regex, $filepath))
    {
        $desirable[] = $filepath;
    }
}

// OPTIONAL: SORT THE FILE NAMES?  MAYBE?
sort($desirable);

// COLLECT THE DATA FROM THE DESIRABLE FILES
$collected = NULL;
foreach ($desirable as $name)
{
    $collected .= PHP_EOL . file_get_contents($name);
}
$collected = trim($collected);

// WRITE THE COMBINED FILE DATA (a document called "combined.txt" )
file_put_contents('storage' . DIRECTORY_SEPARATOR . 'combined.txt', $collected);

// SHOW A LINK SO WE CAN SEE THE COMBINED DATA
$link = '<a target="_blank" href="' . 'storage' . DIRECTORY_SEPARATOR . 'combined.txt' . '">SEE THE FILE</a>' . PHP_EOL;
echo $link;

Open in new window

0
 
LVL 55

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41786138
Mod to ensure file is empty
<?php
$output = 'combined.txt';
$files = glob("*.edi_5");
unlink($output);
foreach($files as $f) {
    file_put_contents($output, file_get_contents($f), FILE_APPEND);
}

Open in new window

0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41786141
so i do
implode $myfiles =>'combined.txt' ?
Not exactly.  Whenever you're unsure about how a PHP function works, you can look it up on PHP.NET.  Example:
http://php.net/manual/en/function.implode.php

PHP implode() is used to turn an array into a string, with optional "glue" character(s).  It would create the string you would later write with file_put_contents().  The name of the output file would be used in file_put_contents(), not in implode().
0
 
LVL 1

Author Comment

by:Jasmine Ikhreishi
ID: 41787617
But they dont have edi_5 at the end, many of them have geh2_4 or h343_4 , there just random
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 41787639
This expert suggested creating a Gigs project.
But they dont have edi_5 at the end...
These are the kinds of "details" that we really, really need to know about if we are going to help you!  

You can provide us with a good-sized sample of known endings.  Or you can provide us with a written set of rules that define the endings.  Rules might be something like "three to five lower-case letters and numbers, followed by a single underscore, followed by a single digit."

The reason this is important is because glob() or regex matching uses written rules to find the file names that match your needs.  Without well-defined rules, we will miss important files or include unwanted files, and neither of those outcomes is acceptable.

You might also want to think about putting all the files you want into their own directory.  Then you could just say "process all files in this directory, no matter what their names."  Just a thought...
1
 
LVL 55

Expert Comment

by:Julian Hansen
ID: 41787659
... or you can read the code, try to understand what is going on - posting back here for clarification and then modify the code to suite your particular circumstances. By working through the code and understanding it

a) You will learn something new
b) You will be able to maintain and extend the code without having to rely on external input.

Rather than trying to find an Expert to give you the exact answer - get into the code samples posted and understand what they are doing - then modify them to suit your particular requirements.
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
how to use a switch statement with heredoc 11 33
What does this formatting equate to? 7 18
Restricting the scope of variables to private in OOP 4 22
Log in through ID 5 17
Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question