Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In-place processing with grep

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!

like image 767
Daniel Standage Avatar asked Oct 20 '10 15:10

Daniel Standage


People also ask

Can grep modify files?

Search and edit text files by using the following commands. grep: The grep command allows you to search inside a number of files for a particular search pattern and then print matching lines. For example, grep blah file will search for the text "blah" in the file and then print any matching lines.

Can we use grep and sed together?

This collection of sed and grep use cases might help you better understand how these commands can be used in Linux. Tools like sed (stream editor) and grep (global regular expression print) are powerful ways to save time and make your work faster.

How do you grep a shell script?

The grep command searches through the file, looking for matches to the pattern specified. To use it type grep , then the pattern we're searching for and finally the name of the file (or files) we're searching in. The output is the three lines in the file that contain the letters 'not'.


1 Answers

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 
like image 54
Alexey Avatar answered Sep 18 '22 19:09

Alexey