We have a server that logs transactions to a file. I want to write a script that will delete the first 50 lines of the file daily without renameing the file or moving the file.
In early sed versions you can run this script
sed '1,3d'
I don't remember the option that forces to overwrite the file with the modified text, but I think is -i
---------- Post updated at 02:00 PM ---------- Previous update was at 01:59 PM ----------
PS: In my script I delete lines 1 to 3
-i is the option. But that's possible not widely available (certainly on UNIX).
Another option is ed:
$ cat file1
1
2
3
4
5
$ ed file1 << !
1,3d
w
q
!
$ cat file1
4
5
(and of course perl will do it easily!)
Could awk read the file, line-by-line into an array
then starting at element 51 begin writing back out to the same file?
cat file | awk ' NR > 50 ' > file
cat file | sed -n "51,$ p" > file
perl -i -ne ' if($. > 50) { print $_ ; } ' file
Not like this:
awk 'NR >= START {X[NR]=$0} END {for( x = START; x<=NR; x++ ) print X[x] }' START=51 file1 > file1
But you might get away with it like this:
awk 'NR >= START {X[NR]=$0} END {for( x = START; x<=NR; x++ ) print X[x] > "file1"}' START=51 file1
Some UUOC's there!
printf '1,50d\nwq!\n' | ex -s myFile
{ rm myFile; sed -e '1,50d' > myFile; } < myFile
use -i option in sed
-i option will affect the changes in to the file. as your asking without renaming the file or moving the file
sed '1,50d' Log_file.txt
[OR]
sed -n -i '1,50!p' a
execute the above command using crontab, for daily removing.
using perl:-
perl -i -wpe ' $_="" if $. <= 50;' infile.txt
:p;)