1

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?

5

Don't use sed -i - it would overwrite your original file.

Use grep instead.

grep "text to find" input.txt > output.txt
2

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
0

You can use grep. Lets say you want search in the file source_file , and the second file where you have the lines that you want to search from is input_file. Use

    grep -f input_file source_file > output_file

Let's say your source_file is

    Humpty Dumpty sat on a wall
    Humpty Dumpty had a great fall
    All the King's horses and 
    All the Queen's men
    COuld not put Humpty together again

And input file is

    Humpty
    Queen

The your output fie would be

    Humpty Dumpty sat on a wall
    Humpty Dumpty had a great fall
    All the Queen's men
    COuld not put Humpty together again
0

sed -i is for inplace editing:

from man sed

-i[SUFFIX], --in-place[=SUFFIX]
      edit files in place (makes backup if SUFFIX supplied)

sed is a good choice, but you could also use awk

 awk '/<your_pattern>/' foo > bar

Example

$ cat foo
foo bar foobar
bar foo bar
bar foo

$ awk '/foobar/' foo > bar

$ cat bar
foo bar foobar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.