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

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

     # sed script to change "foo" to "bar" only on the first occurrence
     1{x;s/^/first/;x;}
     1,/foo/{x;/first/s///;x;s/foo/bar/;}
     #---end of script---
    

    or, if you prefer: Editor's note: works with GNU sed only.

    sed '0,/foo/s//bar/' file 
    

    Source

提交回复
热议问题