19

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
user000001
  • 32,226
  • 12
  • 81
  • 108
anshul gupta
  • 197
  • 1
  • 1
  • 8

4 Answers4

38

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
Kent
  • 189,393
  • 32
  • 233
  • 301
9

If you have GNU awk, you can try the function length on a array:

awk '{split($1,A,"."); print A[length(A)]}'
oliv
  • 12,690
  • 25
  • 45
3

Why not:

$ awk '{print A[split($3,A,".")],$0}' input.txt

Hope it helps!

Lacobus
  • 1,590
  • 12
  • 20
1

Kent already gave you the split() answer but you don't need split creating/using an array for this, e.g. with GNU awk for gensub():

$ awk '{print gensub(/.*\./,"",1,$3), $0}' file
ghi 123 456 abc.def.ghi 789
rfv 321 654 qaz.wsx.edc.rfv 987
Ed Morton
  • 188,023
  • 17
  • 78
  • 185