duanduan8439 2017-07-24 09:49
浏览 178

使用PHP删除.txt文件中的重复行

I have multiple txt files with a directory. The text files all contain the same header. I am reading in all the txt files and outputting it all to one file.

Since each individual file contains the same header, It is inserting all of them into the new merged file. How can I remove all the headers in the new merged file and leave one just at the top?

I have been looking at the sort command in unix.

sort filename | uniq

This command works, but removes all other data that is duplicate. Is there anyway to remove just the specific string "This is a header" but leave one at the top?

Current Code

$header = array( "XX-XXXXXXXXX-XXXXXXX-X        XXXXXXXXXXXX" );


$files = glob( "/path/to/folder/*.txt" );

$output_file = "newfile_".date( "YmdHis" ).".txt";

$out = fopen( $output_file, "w" );

foreach( $header as $inputHeader ) {

    fwrite( $out, $inputHeader );
}

    foreach( $files as $file ) {

        $in = fopen( $file, "r" );

            while ( $line = fgets( $in ) ) {

                if( $header !== $line ) {

                    fwrite( $out, $line );

                }

            }

        fclose( $in );

     }

fclose( $out );

The Line that is duplicated many times This is the duplicate

  • 写回答

4条回答 默认 最新

  • douguwo2275 2017-07-24 09:59
    关注

    Try inputting the header at the start of writing, then check for it later on when you are reading the lines

    //cache our header lines
    $header = "Header line";
    
    $files = glob( "/path/to/files*.txt" );
    
    //print_r($files);
    
    $output_file = "newfile".date( "YmdHis" ).".txt";
    
    $out = fopen( $output_file, "w" );
    
    //input the header line at the top of our new file
    
    fwrite( $out, $header);
    
    
    
    foreach( $files as $file ) {
    
        $in = fopen( $file, "r" );
    
            while ( $line = fgets( $in ) ) {
                //header check, dont output header lines to new file
                if($header !== preg_replace('/\s+/', '', $line)){
                     fwrite( $out, $line );
                }
            }
    
        fclose( $in );
    }
    
    fclose( $out );
    
    评论

报告相同问题?

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装