Simd
Simd

Reputation: 21253

How to add a time stamp on each line of grep output?

I have a long running process running and I want to monitor its RAM usage. I can do this by watching top. However I would like to be able to log out and have a record written, every minute say, to a shared disk space instead.

My solution which works is:

nohup top -b -d 60 -p 10036|grep 10036 >> ramlog.txt &

But I would like to know when each line is outputted too. How can I modify the one-liner to add this information on each line?

I know about screen and tmux but I would like to get this simple one-liner working.

Upvotes: 0

Views: 1184

Answers (2)

0xZ3RR0
0xZ3RR0

Reputation: 596

Generally, to add a timestamp to each line of grep output you can chain grep with awk like this:

grep --line-buffered "PATTERN" "$FILE" | awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }'

Here awk '{ print strftime("%Y-%m-%d %H:%M:%S"), $0 }' means to print the timestamp and then the line (from grep). Or in more detail, strftime("%Y-%m-%d %H:%M:%S") formats the current date and time as YYYY-MM-DD HH:MM:SS and the $0 variable contains the entire line of input which was fed into awk.

Important: make sure to pass the --line-buffered argument to grep to ensure each line is printed without delay. Otherwise, grep will only return after it has inspected the whole input file, which might never finish if the input file is a stream.

Upvotes: 1

John Kugelman
John Kugelman

Reputation: 361645

You could add a loop that reads each line from grep and prepends a date. Make sure to use grep --line-buffered to ensure each line is printed without delay.

nohup top -b -d 60 -p 10036 |
    grep --line-buffered 10036 |
    while read line; do echo "$(date): $line"; done >> ramlog.txt &

Upvotes: 4

Related Questions