In-place processing with grep

Viewed 22845

I've got a script that calls grep to process a text file. Currently I am doing something like this.

$ grep 'SomeRegEx' myfile.txt > myfile.txt.temp
$ mv myfile.txt.temp myfile.txt

I'm wondering if there is any way to do in-place processing, as in store the results to the same original file without having to create a temporary file and then replace the original with the temp file when processing is done.

Of course I welcome comments as to why this should or should not be done, but I'm mainly interested in whether it can be done. In this example I'm using grep, but I'm interested about Unix tools in general. Thanks!

9 Answers

Store in a variable and then assign it to the original file:

A=$(cat aux.log | grep 'Something') && echo "${A}" > aux.log

cat myfile.txt | grep 'sometext' > myfile.txt

This will find sometext in myfile.txt and save it back to myfile.txt, this will accomplish what you want. Not sure about regex, but it does work for text.

Related