1

I have following data extracted from the MySQL database to create labels.


BREAK

Name:RAJ
Company:ABC
Order Number:101

Order Details:
Item1
Item20
Item3

BREAK

Name:RAJ
Company:ABC
Order Number:101

Order Details:
2 x Item1
2 x Item2
2 x Item3

BREAK

Name:RAJ
Company:ABC
Order Number:101

Order Details:
5 x Item4
5 x Item5
5 x Item2

I wrote some code to find the position of BREAK in PHP and it can generate lines number like below.

2
14
26
36

I want a file for the contents that are between line 2 and 14 in one file and 26 to 36 in one file. I am working in php and tried using sed from shell_exec function however if I read this output and generate sed command, I don't get first 2 number together.

What I am expecting is below.

sed -n 2,14p file1.txt
sed -n 26,36p file2.txt

Any suggestion either in php or shell script?

1
  • I went ahead and assumed you meant creating not crating files. :)
    – Christian
    Apr 25, 2012 at 19:12

1 Answer 1

0

Use array_slice() for getting ranges in an array. My solution is very hard coupled to your requirements, meaning every first line is a starting range number and the following the end range.

// the lines from which will be read
$lines = "1
5
16
26";
// split these numbers above into an array
$lines = explode(PHP_EOL, $lines);

// the source file where the ranges will be taken off
$file = file('file.txt');


for($i = 0; $i < count($lines); $i+=2) {
  $rangeStart  = $lines[$i];
  $rangeLength = $lines[$i+1] - $lines[$i];

  // slice out the ranges, beware the second parameter is the length not the offset!
  $ranges[] = array_slice($file, $rangeStart, $rangeLength);

}

print_r($ranges);

But it would be a lot easier to do it automatically on your source file/text/string (?) directly, if this is possible.

$file = file('file.txt');
$len  = count($file);

$output  = array();
$current = array();
for($i = 0; $i < $len; $i++) {
  $data = trim($file[$i]);

  if ($data != 'BREAK') {
    $current[] = $data;
  } else {
    $output[] = implode(PHP_EOL, $current);
    $current  = array();
  }
}

print_r($output);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.