0

I tried to replace the existing file with ">" symbol but it ends up with empty file, can someone help me to check my code?

$ grep -c "ERROR" server.log.2016-03-15 
633
$ grep "ERROR" server.log.2016-03-15 >error 
$ grep -c "ERROR" error 
633
$ grep -c "Login errors" error 
95
$ grep "ERROR" error | grep -v "Login errors" >error
$ grep -c "ERROR" error 
0
Lawrence Loh
  • 233
  • 1
  • 2
  • 9

1 Answers1

1

You can't read from and write to the same file in a single shell command, because > truncates the output file (i.e., in this case also the input file) before the command is executed.

The customary idiom in this case is to do something like:

... inputfile > /tmp/tmp$$ && mv /tmp/tmp$$ inputfile

In other words: output to an intermediate temporary file, and then, if the preceding command succeeded (&&), replace the original file.

Note that there are pitfalls when you simply recreate a file with the same name as the original: if the original file was a symlink, the link is lost, if the original file had special permissions, they are lost, ...

Applied to the command in question, we get:

grep "ERROR" error | grep -v "Login errors" > /tmp/tmp$$ && mv /tmp/tmp$$ error
mklement0
  • 382,024
  • 64
  • 607
  • 775