Bash: add timestamp prefix to log without using "ts"

261 Views Asked by At

I have a bash command which prints a lot of content over time. Now i want to add the current timestamp as prefix before every line. I am aware that there exists the "ts" command of the library "moreutils". Unfortuanly i can't use it. Is there another simple way to do it?

My current idea was to use "sed" in combination with the "date" command. It looks quite good but the problem is that the timestamp does not change.

./echo_hello_every_second.sh | sed -e "s/.*/$(date '+%F %H:%M:%N: ')&/"
2022-08-01 15:59:443158143: Hello
2022-08-01 15:59:443158143: Hello
2022-08-01 15:59:443158143: Hello
2022-08-01 15:59:443158143: Hello
2022-08-01 15:59:443158143: Hello
2022-08-01 15:59:443158143: Hello
2022-08-01 15:59:443158143: Hello

Is there a way to force a reexecution of the "time" command within "sed" with every new input line?

I am also open to other suggestions.

1

There are 1 best solutions below

3
M. Nejat Aydin On

If you have GNU sed (for the e command), and input lines don't contain a single quot:

while :; do echo Hello; sleep 1; done |
sed -e "s/.*/printf '%s: %s\\\\n' \"\$(date '+%F %H:%M:%S.%N')\" '&'/" -e e

If they can contain single quotes, then

while :; do echo Hello; sleep 1; done |
sed -e "s/'/'\\\\''/g" \
    -e "s/.*/'&'/"     \
    -e "s/^''//"       \
    -e "s/''$//"       \
    -e 's/^/printf "%s: %s\\n" "$(date "+%F %H:%M:%S.%N")" /' \
    -e e

A plain bash solution would be much simpler:

while :; do echo Hello; sleep 1; done |
while IFS= read -r line; do
    printf '%s: %s\n' "$(date '+%F %H:%M:%S.%N')" "$line"
done