Frage

I'm trying to convert epoch time in a string, replacing the time string but leaving the rest of the string intact as-is. I've managed to get that figured out, but due to the FS separator regex I've used I lose the previous formatting of a=string[space]b=string[space]

normally listing the file:

cat file

output:

h=10.130.14.28 u="sometext" s=111 X=- t=1386748760 T=132641284 Ts=123 act=1 cat="0x0000000000"

With the below awk string I've converted the epoch time, but I would like to maintain the previous formatting.

cat file | awk 'BEGIN {FS= "[\= ]"} {$10="\""strftime("%I:%M:%S%p %Z %m-%d-%G",$10)"\""} {print}'

output - lost the equals character in the a=string[space]b=string[space] formatting

h 10.130.14.28 u "sometext" s 111 X - t "11:59:20PM PST 12-10-2013" T 132641284 Ts 123 act 1 cat "0x0000000000"

I think I might need to use OFS with awk or maybe pipe to sed, but not too sure how to do it. When I use { OFS "=" } it just adds a = in every field separator - so I got close but not exactly what I need.

cat file | awk 'BEGIN {FS= "[\= ]"} {OFS= "="} {$10="\""strftime("%I:%M:%S%p %Z %m-%d-%G",$10)"\""} {print}'

output:

h=10.130.14.28=u="sometext"=s=111=X=-=t="11:59:20PM PST 12-10-2013"=T=132641284=Ts=123=act=1=cat="0x0000000000"

My ultimate goal is to tail a log outputting these string and dynamically convert the epoch time.

War es hilfreich?

Lösung

You can try:

awk '
{
    match($0, /t=([^[:blank:]]*)[[:blank:]]/, a)
    ss= "t=\""strftime("%I:%M:%S%p %Z %m-%d-%G",a[1])"\" "
    sub(/t=[^[:blank:]]*[[:blank:]]/,ss)
    print
}' file

Explanation:

  • $0 is the whole line except for the trailing newline. We do not need to specify any field separators since we work on the whole line and not particular fields.
  • The regular expression /t=([^[:blank:]]*)[[:blank:]]/ searches for the string "t=" followed by a set of non-blanks. Since we have parenthesis around that, that is: ([^[:blank:]]*), we can later refer to that part as a[1].
  • We then format the time string.
  • And we substitute it back into the whole line
  • We print the line
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top