dqkxo44488 2016-04-08 15:33
浏览 61
已采纳

从文本文件-sed中的每一行中删除前两个char

I am using PHP file which execute sed:

shell_exec("C:\\cygwin64\\bin\\bash.exe --login -c 'sed -i -r \'s/.{2}//\' $text_files_path/File.txt 2>&1'");

This statement will delete the first 2 character from file.txt. How to delete the first 2 char from (each line) in the file?

File.text:

< TTGCATGCAAAAATTT
< AAAAAAATTTTGCTGA
< AAGGTTCCCCCTTAGT

Edit 1:

shell_exec("C:\\cygwin64\\bin\\bash.exe --login -c 'sed -i -r 's/^..//' $text_files_path/File.txt 2>&1'");

This works but, it concatenate all lines together: File.text after above command:

TTGCATGCAAAAATTTAAAAAAATTTTGCTGAAAGGTTCCCCCTTAGT
  • 写回答

3条回答 默认 最新

  • duanhuang2804 2016-04-08 16:26
    关注

    Please don't call sed via bash to do something that PHP can do natively. It's a complete anti-pattern. Worryingly, I have seen the exact same thing in another question quite recently...

    I hope you've got plenty of free disk space:

    $input_filename = "$text_files_path/File.txt";
    $output_filename = 'path/to/temp/output.txt';
    
    $input_file = fopen($input_filename, 'rb');
    $output_file = fopen($output_filename, 'wb');
    
    while (($line = fgets($input_file)) !== false) {
        fwrite($output_file, substr($line, 2));
    }
    
    fclose($input_file);
    fclose($output_file);
    
    rename($output_filename, $input_filename);
    

    Open the input file for reading and the temporary output file for writing. Use binary mode in both cases to avoid issues related to different line endings on different systems.

    Read each line of the input and write the substring from the second character to the temporary output.

    Close both files and then overwrite the input with the temporary file.

    Technically this could actually be implemented in-place but the resulting script would be much more complicated and you would run further risk of corrupting your input file if things went wrong.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?