Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

grep

sed

awk

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

Suppose file1:

ram 100 ct 50
gopal 200 bc 40
ravi 50 ct 40
krishna 200 ct 100

file2 should have only the lines containing "ct", which would look like this:

ram 100 ct 50
ravi 50 ct 40
krishna 200 ct 100

Which is the best way to achieve this? I had a file of 200mb. I used grep but I didn't get any result running grep -n ct file1.

like image 550
mkreddy Avatar asked Mar 11 '14 07:03

mkreddy


People also ask

How do I copy a line from one file to another in Linux?

To copy files and directories use the cp command under a Linux, UNIX-like, and BSD like operating systems. cp is the command entered in a Unix and Linux shell to copy a file from one place to another, possibly on a different filesystem.

How do you copy a line in Linux?

To copy a line requires two commands: yy or Y ("yank") and either p ("put below") or P ("put above"). Note that Y does the same thing as yy .


1 Answers

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
like image 103
Jotne Avatar answered Sep 30 '22 12:09

Jotne