How to print matching value of patterned field separator in AWK

awk

In the below command,

cat abc.txt|awk -F"[0-9]+." '{print FS $3}'

Here FS prints [0-9]+.. However, I want the awk to print the matched value by that field separator e.g. "99." . Any idea how can I do it?

Say abc.txt has this below. I want to separate second sentences using number. as FS and print that number. in the output. basically want to print the value of FS …such need came across in several places.

14. Animals  20. features           
1. tiger   1. wild animal
2. cat     2. domestic animal
3. parrot  3. bird with wings

Best Answer

You don't want the value of FS; you want the string which matched FS (which can be different strings on the same line):

> awk -F"[0-9]+." '{ printf "line %3d.: ",NR; 
  if (NF==1) { print "No FS match in this line"; next; }; str=$0; 
  for(j=1;j<NF;j++) { match(str, FS); fs_str=substr(str, RSTART, RLENGTH); 
  printf "_%s_, ",fs_str; str=substr(str, RSTART+RLENGTH)}; print ""; }' file
line   1.: _14._, _20._, 
line   2.: _1._, _1._, 
line   3.: _2._, _2._, 
line   4.: _3._, _3._,
Related Question