Extract all the ocurrences in a String

Hi.

I'll do my best to write correctly ( I'm from Spain ).

I have to create a sh to read from a flat file. Each field is delimited by ":", so each line could be like this:

field1:field2:field3 and so on.

I will create a file which can read a flat file containing 1..n fields.

I've done all the process, reading all the lines. Each line I read, I'm invoking to extract the substring, having the pattern ":".

echo $a | awk '{FS=":"}{print $1}{print $2}'

Where $a is the current line in the file. Since I don't know how many fields per line that the file can have, I need some way to know how many delimiters have the line.

print $1 prints all the text up to the delimiter.
print $2 same, until the second delimiter and so on...

There's some parameter that tells me how many delimiters are? ( Just like $@ or $* tells the number or parameters to a function, in example )

Thanks in advance.

Regards.

pd: Sorry for the english :stuck_out_tongue:

I'm almost sure you want awk

awk -F: '{
              print "this line has ", NF, " columns: " $0
              print "these are the fields"
              for(i=1; i<=NF; i++) {
                    print $1
              }

           }' inputfilename 

Jim,

Thanks for your quick reply.

The code you wrote, works fine, this is exactly what I wanted.

Just a note. where you put print $1, must be print $i

Thanks again :slight_smile:

yes - my bad it should be $i.

Just curiosity....

Is there any way to do this without calling awk?

I tried something like:

((i=0))
while [[ $a = *:* ]] ; do
....
((i=i+1))
done

But I'm still a newbie...

#!/bin/ksh

file=inputFile

while IFS=':' read a
do
   set -- $a

   printf "this line has %d columns: %s\n" "$#" "$a"

   cnt=1
   print "these are the fields"
   while [ $cnt -le $# ]
   do
      eval print \$$cnt
      cnt=$(( $cnt + 1 ))
   done
done < ${file}

vgersh99,

Thanks for the code. It works prefectly.

jim mcnamara, vgersh99, thanks again. I've learned a lot today with your tips & codes.