Alex Rivera | Logout

loop over characters in input string using awk

Asked 2011-12-19T15:46:51.730
28

Believe it or not, I can't find the answer to what I would think would be this very basic question.

In awk, how can I loop over the input string character by character? Let's say I just wanted to print them out. Is there an array I can access? Or do I need to use substr?

Basically, something like:

echo "here is a string" | awk '
{ for(i=0; i<[length of input string]; i++) 
    printf [value at index i in array x]; 
}'

Frankly, I'm embarrassed.

Edit
Report

1 Answer

25

By default in awk the Field Separator (FS) is space or tabs. Since you mentioned you wanted to loop over each character and not word, we will have to redefine the FS to nothing. Something like this -

[jaypal:~/Temp] echo "here is a string" | awk -v FS="" '
{for (i=1;i<=NF;i++) printf "Character "i": " $i"\n"}' 
Character 1: h
Character 2: e
Character 3: r
Character 4: e
Character 5:  
Character 6: i
Character 7: s
Character 8:  
Character 9: a
Character 10:  
Character 11: s
Character 12: t
Character 13: r
Character 14: i
Character 15: n
Character 16: g
answered 2011-12-19T16:18:25.340

Your Answer