使用unix& php将子文件夹的名称放入.csv

时间:2012-04-11 23:41:50

标签: php unix csv sed cat

我有zip文件,解压缩后,有几个子文件夹,每个子文件夹都包含一个名为report.csv的csv:

the_folder/
    1234/report.csv
    abcd/report.csv
    jklm/report.csv
    5678/report.csv

每个CSV都有列&内容如:

almonds, biscuits, cookies, dog_biscuits 
123, 321, 333, 444
555, 666, 777, 888
444, 551, 555, 999 (and so on for 75 lines or so)

我想将它们放入合并的CSV文件中。我一直在PHP文件中使用exec来执行此操作:

exec("cat /path/the_folder/*/report.csv > /path/combined.csv");

然后使用sed删除重复的“杏仁,饼干,饼干,dog_biscuits”标题行。

现在我需要获取子文件夹的名称并将它们放入combined.csv的行中。

因此,将在CSV(“subfolder_name”)中添加一列,然后在该列中添加该行所来自的文件夹的名称。像

这样的东西
almonds, biscuits, cookies, dog_biscuits, subfolder_name
123, 321, 333, 444, 1234
555, 666, 777, 888, 1234
444, 551, 555, 999, abcd
333, 333, 111, 222, abcd
111, 222, 444, 333, abcd (etc and so on for 300 lines)

最聪明,最简单,最有效的方法是什么?

3 个答案:

答案 0 :(得分:0)

试试这个:

$folder_list = array(); // USE YOUR CODE TO GET FOLDER LIST
$combined_output = "";
$folder_i = 0;
foreach ($folder_list as $folder) {
   $file = file($folder . "/report.csv");
   foreach ($file as $line_i => $line) {
      if (($folder_i == 0 && $line_i == 0) || $line_i > 0) {
         $combined_output .= $line . PHP_EOL;
      }
   }
   $folder_i++;
}

$f = fopen("combined.csv", "w+");
fwrite($f, $combined_output);
fclose($f);

答案 1 :(得分:0)

你可以尝试

$folderList = array (
        "1234/report.csv",
        "abcd/report.csv",
        "jklm/report.csv",
        "5678/report.csv" 
);

$combinedCSV = "result_combine.csv";
$headers = array (
        "almonds",
        "biscuits",
        "cookies",
        "dog_biscuits" 
);
touch ( $combinedCSV );

$fp = fopen ( $combinedCSV, 'w' );
fputcsv ( $fp, $headers ); // Add headers
foreach ( $folderList as $file ) {
    if (($handle = fopen ( $file, "r" )) !== FALSE) {
        while ( ($data = fgetcsv ( $handle, 1000, "," )) !== FALSE ) {
            if ($data [0] == "almonds") // Remove Headers
                continue;
            fputcsv ( $fp, $data );
        }
        fclose ( $handle );
    }
}

fclose($fp);

我希望它有所帮助

谢谢

答案 2 :(得分:0)

TXR:

@header
@(output)
@header, subfolder_name
@(end)
@(next :args)
@(collect)
@folder/@subfolder/@file.csv
@  (next `@folder/@subfolder/@file.csv`)
@header
@  (collect :vars ())
@line
@    (output)
@line, @subfolder
@    (end)
@  (end)
@(end)

执行命令

$ txr catname.txr folder/*/*.csv
animal, sound, subfolder_name
dog, bark, abcd
horse, neigh, abcd
cat, meow, efgh
cow, moo, efgh

数据:

$ ls -R folder/
folder/:
abcd  efgh

folder/abcd:
a.csv

folder/efgh:
e.csv

$ cat folder/abcd/a.csv 
animal, sound
dog, bark
horse, neigh

$ cat folder/efgh/e.csv 
animal, sound
cat, meow
cow, moo