Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 616
anshul gupta Avatar asked Sep 26 '16 12:09

anshul gupta


People also ask

What does split do in awk?

The awk function split(s,a,sep) splits a string s into an awk array a using the delimiter sep. Variable hms is an array so hms[2] is 34 . The last three statements are equivalent, but the last two more convenient for longer arrays. In the second you can specify the start index and number of elements to print.

Which function in awk is used to divide a string into pieces separated by the field separator and store the pieces in an array?

Before splitting the string, patsplit() deletes any previously existing elements in the arrays array and seps . Divide string into pieces separated by fieldsep and store the pieces in array and the separator strings in the seps array.

How do you declare an array in awk?

AWK has associative arrays and one of the best thing about it is – the indexes need not to be continuous set of number; you can use either string or number as an array index. Also, there is no need to declare the size of an array in advance – arrays can expand/shrink at runtime.


1 Answers

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
like image 165
Kent Avatar answered Oct 17 '22 09:10

Kent