1

我有一个包含这样内容的文本文件

   customer-1 Product-2
   customer-1 Product-3
   customer-1 Product-7
   customer-2 Product-20
   customer-2 Product-12
   ...

我想格式化它

  customer-1 Product-2, Product-3, Product-7, Product-20
  customer-2 Product-20, Product-12
  ...

如何在shell脚本或php中做到这一点?

谢谢

4

3 回答 3

2

将您的文件通过管道传输到此 awk 脚本。BOF 中会多出一行,如果需要删除,请使用“head”。

awk 'BEGIN { one = ""; } { if ( one != $1 ) { printf("\n%s %s",$1,$2); one = $1; } else { printf(" %s",$2); } } END { printf("\n"); }'
于 2012-06-07T02:11:31.790 回答
2

使用 PHP:

  1. 使用获取文本文件的内容file_get_contents()
  2. explode()每个换行符上的结果字符串\n
  3. 循环遍历结果数组并explode()在每个空间上

然后,您会将数据加载到多维数组中,并可以循环将其转换为您需要的格式。

添加代码示例(未测试):

$file = file_get_contents('../path/to/file.txt');
$rows = explode('\n', $file);

$customers = array();

foreach($rows as $row) {
    $rowPieces = explode(' ',$row);
    $customers[$rowPieces[0]][] = $rowPieces[1];
}

foreach($customers as $c => $products) {
    $customers[$c] = implode(', ',$products);
}

echo implode('\n', $customers);
于 2012-06-07T02:12:44.900 回答
1

这就是你可以分解它的方式:

  • 加载内容
  • 每条线,找到客户和产品
  • 对每个客户的产品进行分组
  • 输出

例如:

// preg_match_all will find all "customer-" (digits) and "product-" (digits)
if (preg_match_all('/(customer-\d+)\s*(product-\d+)/i', $s, $matches, PREG_SET_ORDER)) {
        $purchases = array();
        foreach ($matches as $match) {
                // $match[1] contains customer id
                // $match[2] contains product id
                $purchases[$match[1]][] = $match[2];
        }
        // $purchases now contains a list of products, grouped by customer
        foreach ($purchases as $customer => $products) {
                echo $customer, ' ', join(', ', $products), PHP_EOL;
        }
}
于 2012-06-07T02:12:02.890 回答