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

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

    If anyone came here to replace a character for the first occurrence in all lines (like myself), use this:

    sed '/old/s/old/new/1' file
    
    -bash-4.2$ cat file
    123a456a789a
    12a34a56
    a12
    -bash-4.2$ sed '/a/s/a/b/1' file
    123b456a789a
    12b34a56
    b12
    

    By changing 1 to 2 for example, you can replace all the second a's only instead.

提交回复
热议问题