Home > database >  AWK positional variables processing
AWK positional variables processing

Time:11-06

This my data from db

"1.1.1.1|1636057103"

How can i use something like date '%d.%m.%y %H:%M:%S' -d @1636057103 inside AWK to convert unix timestamp in $2 variable to get output like:

"1.1.1.1 - 04.11.21 22:18:23"

?

Thx!

CodePudding user response:

With GNU awk and its strftime:

awk -F '["|]' '{$3=strftime("%d.%m.%Y %H:%M:%S", $3); print "\"" $2 " - " $3 "\""}' file

or

awk -F '["|]' '{$0=strftime("\"" $2 " - %d.%m.%Y %H:%M:%S\"", $3)}1' file

Output:

"1.1.1.1 - 04.11.2021 21:18:23"

See: 9.1.5 Time Functions

CodePudding user response:

With bash, a regex and date:

f=$(< file) # read file to variable f
[[ $f =~ \"(.*)\|(.*)\" ]] && date  "\"${BASH_REMATCH[1]} - %d.%m.%y %H:%M:%S\"" -d "@${BASH_REMATCH[2]}"

Output:

"1.1.1.1 - 04.11.21 21:18:23"

CodePudding user response:

Assumptions:

  • data contains literal double quotes as bookends
  • data is stored in a variable
  • reformatted data to be stored in a new variable with double quotes as bookends

Using some basic bash parameter substition/expansion operators:

data='"1.1.1.1|1636057103"'
data="${data//\"}"                 # strip double quotes
ip="${data%|*}"                    # break into ip and ...
epoch="${data#*|}"                 # epoch

# build new variable:

printf -v newddata "\"${ip} - '%(%d.%m.%y %H:%M:%S)T' @${epoch}" "\""
echo "${newdata}"

This generates:

"1.1.1.1 - 04.11.21 15:18:23"

NOTE: the hour component is off from OP's sample output likely due to difference in our timezones

  • Related