How to redirect grep command output to same file

Hi Everyone,

Can anyone please tell me, how can I redirect the grep command output to same file. I am trying with below command but my original file contains no data after executing the command.

$grep pattern file1 > file1

Kind Regards,
Eswar

Hi.

With grep, you can't.

This (very recent - and spookily similar) thread might help: Redirect overwrites itself

Hi Eshwar,

do it with "sed" rather. The "-i" switch has the "in-place" editing.

sed -ni '/pattern/p' file

However if something goes wrong, you can backup the file . The "-i" switch has that facility.

sed -ni.bak '/pattern/p' file

This also create a backup of the original file in addition to doing your job file - file.bak

Regards,
Gaurav.

Gaurav,

In my sun solaries system sed does not have -i option.

Can anyone please suggest any other alternative for this.

Regards
Eswar.

Hi,

Do it with perl then -

 perl -wlni.bak -e 'print if /pattern/' file

does the same thing as the above sed does.

Regards,
Gaurav.

Its available with GNU sed only and not with standard distributions of sed.

---------- Post updated at 12:41 PM ---------- Previous update was at 12:41 PM ----------

There is a way - non standard but.

sponge

command