In-place processing with grep

In general, this can't be done. But Perl has the -i switch:

perl -i -ne 'print if /SomeRegEx/' myfile.txt

Writing -i.bak will cause the original to be saved in myfile.txt.bak.

(Of course internally, Perl just does basically what you're already doing -- there's no special magic involved.)


No, in general it can't be done in Unix like this. You can only create/truncate (with >) or append to a file (with >>). Once truncated, the old contents would be lost.


sponge (in moreutils package in Debian/Ubuntu) reads input till EOF and writes it into file, so you can grep file and write it back to itself.

Like this:

grep 'pattern' file | sponge file

Perl has the -i switch, so does sed and Ruby

sed -i.bak -n '/SomeRegex/p' file

ruby -i.bak -ne 'print if /SomeRegex/' file

But note that all it ever does is creating "temp" files at the back end which you think you don't see, that's all.

Other ways, besides grep

awk

awk '/someRegex/' file > t && mv t file

bash

while read -r line;do case "$line" in *someregex*) echo "$line";;esac;done <file > t && mv t file