首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何格式化此文本文件

如何格式化此文本文件
EN

Stack Overflow用户
提问于 2012-06-07 10:06:32
回答 3查看 354关注 0票数 1

我有一个文本文件,内容如下

代码语言:javascript
复制
   customer-1 Product-2
   customer-1 Product-3
   customer-1 Product-7
   customer-2 Product-20
   customer-2 Product-12
   ...

我想把它格式化为

代码语言:javascript
复制
  customer-1 Product-2, Product-3, Product-7, Product-20
  customer-2 Product-20, Product-12
  ...

如何在shell脚本或php中实现?

谢谢

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-06-07 10:11:32

通过管道将您的文件传输到此awk脚本。将在BOF中有一个额外的行,如果你需要删除它,使用'head‘。

代码语言:javascript
复制
awk 'BEGIN { one = ""; } { if ( one != $1 ) { printf("\n%s %s",$1,$2); one = $1; } else { printf(" %s",$2); } } END { printf("\n"); }'
票数 2
EN

Stack Overflow用户

发布于 2012-06-07 10:12:45

使用PHP:

在每个新行\n

  • loop上使用file_get_contents()

  • explode()获得文本文件的内容,通过在每个空格

上使用结果数组和explode()获取文本文件的内容

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

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

代码语言:javascript
复制
$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);
票数 2
EN

Stack Overflow用户

发布于 2012-06-07 10:12:03

下面是你可以如何分解它:

  • 为每行加载内容
  • ,查找客户和产品
  • 组 products per customer
    • output

例如:

代码语言:javascript
复制
// 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;
        }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10924751

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档