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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)