LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Using grep to remove line and write back to same file!? (https://www.linuxquestions.org/questions/linux-newbie-8/using-grep-to-remove-line-and-write-back-to-same-file-788285/)

KFC123 02-10-2010 01:07 PM

Using grep to remove line and write back to same file!?
 
I search the forum and get some help to remove a line starting with specific word with grep. Here is what I found

grep -v '^cc$' data.txt

Here I remove all lines with on 'cc' in that line. But I want the result write back to data.txt

I try several ways

grep -v '^cc$' data.txt > output.txt # works but to another file
echo `grep -v '^cc$' data.txt` > data.txt # didn't work, all carets gone, become one line
grep -v '^cc$' data.txt > data.txt # data.txt is empty after running this

How can I save the result of grep to the input file?

Thanks.

Lord Mortus 02-10-2010 01:13 PM

You can try
grep -v '^cc$' data.txt >> data.txt

the >> appends the output so it will add it to the end of your target file.

rweaver 02-10-2010 01:14 PM

Grep has some interesting options and is a good tool, but generally I wouldn't consider that a job for grep... That's a job for sed or awk (or perl even).

Code:

sed -i '/^cc/d' data.txt
If you're really insistent on grep--

Code:

grep -v '^cc$' data.txt > output.txt && mv -f output.txt data.txt

KFC123 02-10-2010 01:34 PM

I don't want to create a intermediate file but sed works perfectly for my case. Thanks a lot.

Quote:

Originally Posted by rweaver (Post 3859385)
Grep has some interesting options and is a good tool, but generally I wouldn't consider that a job for grep... That's a job for sed or awk (or perl even).

Code:

sed -i '/^cc/d' data.txt
If you're really insistent on grep--

Code:

grep -v '^cc$' data.txt > output.txt && mv -f output.txt data.txt


rweaver 02-10-2010 02:06 PM

Sed is a spectacular application, you can really replace grep with it entirely if you want to.

Check out the sed1line.txt for some spectacular examples of sed being a handy tool.


All times are GMT -5. The time now is 11:55 PM.