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

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

    Quite a comprehensive collection of answers on linuxtopia sed FAQ. It also highlights that some answers people provided won't work with non-GNU version of sed, eg

    sed '0,/RE/s//to_that/' file
    

    in non-GNU version will have to be

    sed -e '1s/RE/to_that/;t' -e '1,/RE/s//to_that/'
    

    However, this version won't work with gnu sed.

    Here's a version that works with both:

    -e '/RE/{s//to_that/;:a' -e '$!N;$!ba' -e '}'
    

    ex:

    sed -e '/Apple/{s//Banana/;:a' -e '$!N;$!ba' -e '}' filename
    

提交回复
热议问题