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

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

    Using FreeBSD ed and avoid ed's "no match" error in case there is no include statement in a file to be processed:

    teststr='
    #include 
    #include 
    #include 
    '
    
    # using FreeBSD ed
    # to avoid ed's "no match" error, see
    # *emphasized text*http://codesnippets.joyent.com/posts/show/11917 
    cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | ed -s <(echo "$teststr")
       H
       ,g/# *include/u\
       u\
       i\
       #include "newfile.h"\
       .
       ,p
       q
    EOF
    

提交回复
热议问题