【问题标题】:Creating files based on the line number for printing根据行号创建文件以进行打印
【发布时间】:2012-05-06 12:33:53
【问题描述】:

我从 MySQL 数据库中提取了以下数据来创建标签。

休息 名称:RAJ 公司:ABC 订单号:101 订单详细信息: 项目1 第 20 项 第 3 项 休息 名称:RAJ 公司:ABC 订单号:101 订单详细信息: 2 x 项目 1 2 x 物品 2 2 x 物品 3 休息 名称:RAJ 公司:ABC 订单号:101 订单详细信息: 5 x 物品4 5 x 物品 5 5 x 物品 2

我写了一些代码来查找 BREAK 在 PHP 中的位置,它可以生成如下所示的行号。

2 14 26 36

我想要一个文件中的内容在一个文件中的第 2 行和第 14 行之间以及在一个文件中的第 26 到 36 行之间。我正在使用 php 并尝试使用 shell_exec 函数中的 sed 但是如果我读取此输出并生成 sed 命令,我不会将前 2 个数字放在一起。

下面是我所期待的。

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

在 php 或 shell 脚本中有什么建议吗?

【问题讨论】:

  • 我继续假设您的意思是 creating 而不是 crating 文件。 :)

标签: php shell


【解决方案1】:

使用array_slice() 获取数组中的范围。 我的解决方案很难满足您的要求,这意味着每一行都是一个起始范围编号,然后是结束范围。

// 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);

但是如果可能的话,直接在您的源文件/文本/字符串 (?) 上自动执行它会很多更容易。

$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);

【讨论】:

    猜你喜欢
    • 2014-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多