copy lines containing word from one file to another file in linux

后端 未结 4 1757
南旧
南旧 2021-02-10 01:10

I want to copy lines containing certain words from file1 to file2.

Suppose file1:

ram 100 ct 50
gopal 200 bc 40
ra         


        
相关标签:
4条回答
  • 2021-02-10 01:16
    egrep -n '\bct\b' file1 > file2
    

    By the way, grep -n selects lines together with line numbers. If that's not your intention then grep ct file1 > file2 would suffice.

    0 讨论(0)
  • 2021-02-10 01:24

    I know I'm late, but just wanted to add that you can do this in vim. Create a copy of the file, then run

    :g!/pattern/d
    

    (delete all lines not having the pattern)

    so,

    :g!/^\w+ \d+ ct \d+/      \\ view the lines
    :g!/^\w+ \d+ ct \d+/d     \\ delete lines
    

    More commands can be found here.

    0 讨论(0)
  • 2021-02-10 01:27

    This awk should do

    awk '/ct/' file1 > file2
    

    If position is important

    awk '$3=="ct"' file1 > file2
    awk '$3~/ct/' file1 > file2
    

    last version is ok if ct is part of some in field #3


    Same with grep

    grep ct file1 > file2
    

    -n is not needed, since it prints line number


    Same with sed

    sed -n '/ct/p' file1 > file2
    
    0 讨论(0)
  • 2021-02-10 01:40
    awk '$3=="ct"' file1 > file2
    

    This only filters lines where the third column must exactly match the string ct.

    0 讨论(0)
提交回复
热议问题