How to find LAST subfield after splitting a column
I'm trying to get the last subfield of a string after a split has been applied to it. The problem is I don't know what is the value of the last field in the curved result.
Example Example data
hey,there,how,are,you:bla:bla:foo:bar
hey,this,is ,meaningless,text,and ,the,field,are,more:zoo,zoo
hello,folks,thanks,example:is:this:is:a:line:and:I:could:not:think:of:dummy:data
Now I can get the last field using NF.
Example:
awk -F, '{print $NF}' input
you:bla:bla:foo:bar
more:zoo,zoo
example:is:this:is:a:line:and:I:could:not:think:of:dummy:data
Now if I can get any field using a function split
:
awk -F, '{split($NF,a,":");print a[1]}' input
you
more
example
Now I don't want the Nth field, I need to extract the LAST subfield of the Nth field.
So my desired output is:
bar
zoo
data
Note that something like the following is NOT helpful as it is only useful for the last column.
sed -r 's/(^.*:)(.*)/\2/g' inut
bar
zoo
data
source to share
Use the return value from the function split()
and use it as the array index,
awk -F, '{n=split($NF,a,":");print a[n]}' file
bar
zoo
data
The return value is the number of fields separated by a separator :
that you can apply to any character of your choice.
Quoting from the GNU Awk page for a functionsplit()
split (string, array [, fieldsep [, seps]])
If fieldsep is one space, then any leading whitespace goes to seps [0] and any trailing whitespace goes to seps [n] , where n is the return value of split () (ie, the number of elements in the array) ...
source to share
@inian's solution is more general, 2 alternatives for your 5th field and LAST sub-element. In both cases, I assume there are no noisy ';' or ':' (escaped or on-line) as in your example data.
sed version (5th field assumed)
sed 's/^\([^;]*\)\{5\}[^;]*:\([^;]*\).*/\2/' YourFile
awk version (no separation)
awk -F ',' '{ sub( /.*:/, "", $5); print $5}'
source to share