Move lines matching a pattern from one file to another

后端 未结 5 1397
一向
一向 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:17

    I like the other answers, but just an (obvious) alternative approach in case you are worried about making a mistake in your pattern and want an easy way to rollback:

    grep    'bar' file1 > file2
    grep -v 'bar' file1 > file3
    

    Once you're happy with your results (hint: tee instead of > will allow you to see what's getting written to your files):

    mv file3 file1
    

    Generally I prefer perl to do substitution like in the above answer, but when the regex idiom gets too complicated and you are semi-blindly copying and pasting commands you don't understand, you're not in control of your precious data.

提交回复
热议问题