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

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

    POSIXly (also valid in sed), Only one regex used, need memory only for one line (as usual):

    sed '/\(#include\).*/!b;//{h;s//\1 "newfile.h"/;G};:1;n;b1'
    

    Explained:

    sed '
    /\(#include\).*/!b          # Only one regex used. On lines not matching
                                # the text  `#include` **yet**,
                                # branch to end, cause the default print. Re-start.
    //{                         # On first line matching previous regex.
        h                       # hold the line.
        s//\1 "newfile.h"/      # append ` "newfile.h"` to the `#include` matched.
        G                       # append a newline.
      }                         # end of replacement.
    :1                          # Once **one** replacement got done (the first match)
    n                           # Loop continually reading a line each time
    b1                          # and printing it by default.
    '                           # end of sed script.
    

提交回复
热议问题