Find text in a file and copy it to another file
68,109
Solution 1
Don't use sed -i
- it would overwrite your original file.
Use grep instead.
grep "text to find" input.txt > output.txt
Solution 2
As I understand the question, the op wants to find the text and put it in another file, not the whole line which the text was found.
I would use the grep -o 'pattern' input_file > output_file
.
The -o
flag:
-o, --only-matching
Print only the matched (non-empty) parts of a matching line,
with each such part on a separateoutput line.
Example:
$ cat tmp
01/21/21 - foo
01/22/21 - bar
01/23/21 - foo
01/24/21 - bar
$ grep -o 'foo' tmp > foo
$ cat foo
foo
foo
Solution 3
sed
outputs to stdout
by default. To output to a file, redirect sed
's stdout
to a file using the >
operator (if you want to create a new file) or using the >>
operator (if you want to append the output to an already existing file):
sed '/text/' inputfile > outputfile
sed '/text/' inputfile >> outputfile
Related videos on Youtube
Author by
jordan
Updated on September 18, 2022Comments
-
jordan almost 2 years
Is there any command in Linux to find text in a file and if found then copy it in another file?
Using
sed -i
we can find text but how to copy whole line in another file?