Position of character in word

How can I represent the position of

1

(considering only the 1s after the colon) in the word from field5 and above; counting from right to left.

Input:

TT-124 06-03-14 08-02-10 FAS   CAT1:10
TT-125-1 05-03-14 10-06-08 CAS   CAT2:1010 FAT1:10000
TT-125-3 07-03-14 11-02-06 FAS   FAT1:1101
SS-120-1 05-03-14 09-04-07 FAS   CAT3:100000
AA-121-0 06-03-14 08-03-06 CAS   FAT2:11 CAT1:101100

Output:

TT-124 06-03-14 08-02-10 FAS   CAT1:1
TT-125-1 05-03-14 10-06-08 CAS   CAT2:3 CAT2:1 FAT1:4
TT-125-3 07-03-14 11-02-06 FAS   FAT1:0 FAT1:2 FAT1:3
SS-120-1 05-03-14 09-04-07 FAS   CAT3:5
AA-121-0 06-03-14 08-03-06 CAS   FAT2:0 FAT2:1 CAT1:2 CAT1:3 CAT1:5
awk '{for(i = 5; i <= NF; i++) {split($i, a, ":"); $i = ""; split(a[2], b, "");
  for(j = 1; j <= length(b); j++) {if(b[j] == 1)
    {$i = ($i == "") ? (a[1] ":" length(b) - j) : ($i FS a[1] ":" length(b) - j)}}};
  print $0}' file
1 Like

Given VAR holds the pattern you want to be considered, try sth like:

 for ((i=${#VAR}-1;i>=0;i--)); do [ 1 -eq "${VAR:$i:1}" ] && echo $((${#VAR}-i-1));  done

You can do this within ksh/bash if you wish:-

while read col1 col2 col3 col4 col5
do
   test5="${col5%%1*}"                  # Truncate string after first occurrence of 1
   position="${#test5}"                 # Get the length from zero to full length of $col5
   ((position=$position+1))             # Add one to get the true position of search
   if [ $position -le ${#col5} ]        # Check we actually found the character.
   then
      print "Found character 1 at position $position."
   else
      print "Did not find character 1 in string $col5."
   fi
done < filename

Maybe someone would care to neaten this, but for a large file, it saves spawning multiple awk commands if you are reading it through a shell script.

Works in cygwin but not in Solaris 10 using nawk or /usr/xpg4/bin/awk

try "gawk"

You could also try this:

nawk '{
 for(i = 5; i <= NF; i++) {
  split($i, a, ":"); $i = "";
  for(j=b=length(a[2]);j;j--)
     if(substr(a[2],j,1)+0) $i=$i ($i?FS:"") a[1] ":" b - j}
}1' file