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

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

    As an alternative suggestion you may want to look at the ed command.

    man 1 ed
    
    teststr='
    #include 
    #include 
    #include 
    '
    
    # for in-place file editing use "ed -s file" and replace ",p" with "w"
    # cf. http://wiki.bash-hackers.org/howto/edit-ed
    cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
       H
       /# *include/i
       #include "newfile.h"
       .
       ,p
       q
    EOF
    

提交回复
热议问题