How to use sed to replace only the first occurrence in a file?

前端 未结 23 852
别跟我提以往
别跟我提以往 2020-11-22 04:27

I would like to update a large number of C++ source files with an extra include directive before any existing #includes. For this sort of task, I normally use a small bash s

23条回答
  •  情深已故
    2020-11-22 04:54

    #!/bin/sed -f
    1,/^#include/ {
        /^#include/i\
    #include "newfile.h"
    }
    

    How this script works: For lines between 1 and the first #include (after line 1), if the line starts with #include, then prepend the specified line.

    However, if the first #include is in line 1, then both line 1 and the next subsequent #include will have the line prepended. If you are using GNU sed, it has an extension where 0,/^#include/ (instead of 1,) will do the right thing.

提交回复
热议问题