Move lines matching a pattern from one file to another

后端 未结 5 1401
一向
一向 2021-02-12 23:09

I want to move lines matching certain pattern from file1 to file2. Analogous to operation cut and paste from one file to another in windows

5条回答
  •  遥遥无期
    2021-02-12 23:18

    This might work for you (GNU sed):

    sed -i -e '/bar/{w file2' -e 'd}' file1
    

    An alternative:

    sed -i -e '/bar/w file2' -e '//d' file1
    

    To append to file2, write to a temporary file and use cat to append at the end of file in a bash script, or use:

    sed -i -e '/bar/w tmpfile' -e '$e cat tmpfile >> file2 && rm tmpfile' -e '//d' file1
    

    N.B. For the last solution, only one input file can be modified at a time.

提交回复
热议问题