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

前端 未结 23 1392
别跟我提以往
别跟我提以往 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:33

    You could use awk to do something similar..

    awk '/#include/ && !done { print "#include \"newfile.h\""; done=1;}; 1;' file.c
    

    Explanation:

    /#include/ && !done
    

    Runs the action statement between {} when the line matches "#include" and we haven't already processed it.

    {print "#include \"newfile.h\""; done=1;}
    

    This prints #include "newfile.h", we need to escape the quotes. Then we set the done variable to 1, so we don't add more includes.

    1;
    

    This means "print out the line" - an empty action defaults to print $0, which prints out the whole line. A one liner and easier to understand than sed IMO :-)

提交回复
热议问题