2016-04-08 15:33



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?



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:

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • duanhuang2804 duanhuang2804 5年前

    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));
    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.

    点赞 评论 复制链接分享
  • doulai8128 doulai8128 5年前

    s/^..// That should give you the result you need.

    ^ points to the start of the line then the . will match any character

    点赞 评论 复制链接分享
  • duannuo4620 duannuo4620 5年前

    If you just want to use PHP, then you can explode() the file into individual lines and then use substr() to drop the first two characters before joining the lines back into a single string separated with a new line:

    // Set the results array.
    $result = array();
    // Split the file into lines.
    $file = $text_files_path . '/File.txt';
    $lines = explode("
    ", $file);
    // Cut the first two characters of each line and add to the results array.
    foreach($lines AS $line) {
        $result[] = substr($line, 2);
    // Split the result back into lines.
    $result = implode("
    ", $result);
    点赞 评论 复制链接分享