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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With