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条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容