0

Input file:

01.05.2016 87893938
02.05.2016 35435345  
03.05.2016 35435345  
04.05.2016 12345678

I want to keep only four lines in my file. that means if date 05.05.2016 6905698 is inserted then first line of my file will be removed. I only want to keep last four days data in my file.

Output file:

02.05.2016 35435345  
03.05.2016 35435345  
04.05.2016 12345678  
05.05.2016 89459678
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Nainita
  • 2,862

1 Answers1

2
cp -p file file.orig && \
tail -n 4 file.orig > file && \
rm file.orig

This will copy the original file to a backup copy, retrieve only the last 4 lines from the backup copy, put those 4 lines into the original file name, then remove the backup copy.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • 1
    tail -n4 file > file.orig && cat file.orig > file && rm -f file.orig will be more efficient for large files. It also fails "safely" if someone tried mkdir file.orig first. – Chris Davies May 05 '16 at 13:25
  • true! it could also be improved with mktemp – Jeff Schaller May 05 '16 at 13:28
  • cat your_filename | tail -n 4 > newfilename,,,,writes the last 4 lines to your new file, put this in a script and your can call the script as per your convenience ! – RajuBhai May 05 '16 at 19:16