0

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.

Steffan
  • 1
  • 2

1 Answers1

0

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
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
  • Also consider `printf '%(%F %T)T'` instead of the `date` command if your version of printf supports it and you can live without nanosecond resolution, as you'll get better performance using a builtin over an external command. – tjm3772 Aug 01 '22 at 19:26
  • @tjm3772 Indeed. I always forget the `%T` directive of `printf`. – M. Nejat Aydin Aug 01 '22 at 20:41
  • Thanks for the answer and the working solution! – Steffan Aug 02 '22 at 12:34