awkaix

Print last nth columns on line


How can I print the last 4 columns using awk?

The following solution works fine with numbers:

Command:

echo "1 2 3 4 5" | awk '{print $(NF-3),$(NF-2),$(NF-1),$NF}'

Output:

2 3 4 5

However, when I use text with special characters like below, I get a syntax error:

echo "2023-01-03 01:05:06:       Table test completed      (0 hrs 0 mins 0.009 Secs)" |  awk '{print $(NF-3),$(NF-2),$(NF-1),$NF}'

Output:

> " | awk '{print $(NF-2),$(NF-1),$NF}'
mins 0.009 Secs)
awk: The field -2 cannot be less than 0.

The input line number is 2.
The source line number is 1.

What I am expecting to print out is the below for the above example:

(0 hrs 0 mins 0.009 Secs)

How can I achieve this?


Solution

  • 1st solution: With your shown samples please try following awk code. Simple explanation would be: Using match function of awk. Using regex \(.*\)$ which will match string from ( to till ) if match is found then printing sub-string which will print only matched value(s) as per OP's requirement.

    echo "2023-01-03 01:05:06:       Table test completed      (0 hrs 0 mins 0.009 Secs" |
    awk 'match($0,/\(.*\)$/){print substr($0,RSTART,RLENGTH)}' Input_file
    

    2nd solution: If your Input_file always has "Table test completed" then you can make it more easy then 1st solution, try following then:

    echo "Your_string" |
    awk -F'[[:space:]]+Table test completed[[:space:]]+' '{print $NF}'