I am trying to append usernames to its corresponding ip address in a log file which is being written continuously. But the new lines are getting appended to the previous ones rendering the log file unanalyzable.
Note: Its a web server log file which is continuously being written and my code checks the ip captured in the logs, finds the corresponding username and inserts the username in the beginning of that specific line in the log on a loop. In the first run theres no error but from the second run the lines get messed up as shown below.
for i in $ips
do
...
..
cp $server_log $log_file
sed -i "/^$i/ s/./$user &/" $log_file
cp $log_file $server_log
...
...
done
input file
10.xx.xx.xxx -[12/Feb/2023 02:46:23] "GET /folder/ HTTP/1.1" 200 -
10.xx.xx.xxx -[12/Feb/2023 02:46:44] "GET /folder/ HTTP/1.1" 200 -
10.xx.xx.56 -[12/Feb/2023 02:47:20] "GET /folder2/HTTP/1.1" 200 -
output
user1 10.xx.xx.xxx -[12/Feb/2023 02:46:23] "GET /folder/ HTTP/1.1" 200 -
user1 10.xx.xx.xxx -[12/Feb/2023 02:46:44] "GET /folder/ HT10.xx.xx.56 -[12/Feb/2023 02:47:20] "GET /folder2/HTTP/1.1" 200 -
expected output
user1 10.xx.xx.34 -[12/Feb/2023 02:46:23] "GET /folder/ HTTP/1.1" 200 -
user1 10.xx.xx.34 -[12/Feb/2023 02:46:44] "GET /folder/ HTTP/1.1" 200 -
user2 10.xx.xx.56 -[12/Feb/2023 02:47:20] "GET /folder2/HTTP/1.1" 200 -