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

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

    With GNU sed's -z option you could process the whole file as if it was only one line. That way a s/…/…/ would only replace the first match in the whole file. Remember: s/…/…/ only replaces the first match in each line, but with the -z option sed treats the whole file as a single line.

    sed -z 's/#include/#include "newfile.h"\n#include'
    

    In the general case you have to rewrite your sed expression since the pattern space now holds the whole file instead of just one line. Some examples:

    • s/text.*// can be rewritten as s/text[^\n]*//. [^\n] matches everything except the newline character. [^\n]* will match all symbols after text until a newline is reached.
    • s/^text// can be rewritten as s/(^|\n)text//.
    • s/text$// can be rewritten as s/text(\n|$)//.

提交回复
热议问题