This code

grep -i 'logged in' path-to-file | tail | awk '{ print $6,"logged in at",substr($2,1,8),"on",$1"."; }' | sed 's/"//g'

will output

nickname logged in at 22:06:58 on 2017-12-22.

What I want is to output like this:

nickname logged in at 10:06:58 pm on December 22, 2017.


The unix date command can print dates in whatever format you want to. Using the --date flag you can print a date and time different from the current date and time. However, for the date command to parse the date you have to remove the on in your input date. You can use the following sed command:

sed -r 's,\s+on\s+, ,g'

Combined with your desired output format, you get:

date --date="$(echo '22:06:58 on 2017-12-22' | sed -r 's,\s+on\s+, ,g')" '+%r on %B %d, %Y'

Now, you only have to combine this with your awk command, which can be done easily assuming that you always have the same format "username logged in at date". Note that you can have the on not printed from awk at all, so the sed call is no longer necessary:

while read line
    echo $line | awk '{print $1" "$2" "$3" "$4" "}' | tr -d '\n'
    date --date="$(echo $line | awk '{print $5" "$7}' | tr -d '.')" '+%r on %B %d, %Y'

For the example you gave, this prints (with locale en-NZ):

nickname logged in at 10:06:58 PM on December 22, 2017

  • The only text in my .sh file is the "grep...sed... In your answer the block starting from while read line (which I'actually m totally clueless about), can I simply copy-paste that and replace my script altogether? I think I like your answer, but I'm still confused on how to combine it with my awk... – Joey Dec 22 '17 at 22:30
  • No, use your current command and write | while read ... behind it – msrd0 Dec 22 '17 at 22:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.