anshul gupta anshul gupta - 2 months ago 21
Bash Question

how to access last index of array from split function inside awk?

How can i do this using awk?

Example -

awk '{split($1,A,"."); print A[-1], $1, $2, $3, $4}'


Sample input and output.

Input

123 456 abc.def.ghi 789
321 654 qaz.wsx.edc.rfv 987


Output

ghi 123 456 abc.def.ghi 789
rfv 321 654 qaz.wsx.edc.rfv 987

Answer

If your problem is exactly as the example in your question, take the answer from @muzido, $NF will give you the last field.

If you just want to know the last element of an array by split():

split() function will return you how many elements it has just "splitted", test with your code: awk '{print split($1,A,".")}' file you will see the number. Then you can just use it by:

awk '{n=split($1,A,"."); print A[n]}' file 
# n is the length of array A