0
$ echo "$(lastlog | grep $USER | awk '{print $(NF-5)" "$(NF-3)" "$(NF-4)" "$(NF-2)" "$(NF-1)" "$(NF-0)}')"
Thu 7 Sep 05:56:35 +0100 2023

I want to replace the +0100 bit with BST or GMT if the value is +0000 (I am aware that this output is probably dependent on the locale).

I did test for the value of $(NF-1) to conditionally set a variable, but I don't know how to put the variable within the awk print command.

I also want to put an extra space between $(NF-5) and $(NF-3) when $(NF-3) (the date) is a single digit, but not when it is two digits.

How best can this be done?

1 Answer 1

2

For the time zone, I'd suggest adding an if-statement, since you want to check for two possible values:

if($(NF-1)=="+0000") {zone="GMT"}
else if ($(NF-1)=="+0100") {zone="BST"}
else {zone=$(NF-1)}

Then print the zone variable as defined above. (print zone)

The if-statement cannot be put into a print / printf command directly, whereas if you had only one change e.g. +0000 -> GMT this would work:

print $(NF-1)=="+0000"?"GMT":$(NF-1)

For space-padding $(NF-3), the sound way is using printf.

printf "%2s",$(NF-3)

In summary:

awk '{
    if($(NF-1)=="+0000") {zone="GMT"}
    else if ($(NF-1)=="+0100") {zone="BST"}
    else {zone=$(NF-1)}

    printf "%s %2s %s %s %s %s",$(NF-5),$(NF-3),$(NF-4),$(NF-2),zone,$(NF-0)
}'
1
  • $(NF-1)=="+0000"?"GMT":$(NF-1)=="+0100"?"BST":"$(NF-1) works for two changes, although it starts to get unesthetic Commented Sep 8, 2023 at 23:55

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.