![]() |
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.
|
|
google unix.com
|
|||||||
| Forums | Register | Forum Rules | Links | Albums | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
| UNIX for Dummies Questions & Answers If you're not sure where to post a UNIX or Linux question, post it here. All UNIX and Linux newbies welcome !! |
More UNIX and Linux Forum Topics You Might Find Helpful
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Very urgent :- How to compare string using if statement | jisha | Shell Programming and Scripting | 1 | 01-14-2008 03:41 AM |
| while read loop w/ a nested if statement - doesn't treat each entry individually | littlefrog | Shell Programming and Scripting | 7 | 12-11-2007 09:49 PM |
| For loop statement - catch error | lumdev | Shell Programming and Scripting | 4 | 09-20-2007 08:50 AM |
| if statement in a while loop | bobo | UNIX for Dummies Questions & Answers | 2 | 11-07-2006 12:38 PM |
| Help with if loop (string comparison) | psynaps3 | Shell Programming and Scripting | 4 | 07-07-2006 03:36 AM |
![]() |
|
|
LinkBack | Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
||||
|
if statement in for loop of a string
I am attempting to pass a string into awk and loop through it, and then for every occurrance of a certain character perform an action. In this case, for example, echo 1 for each time character r is found in the string. Except I can't get it to work. Could someone please tell me why?
echo $string | awk '{ for (i=1;i<=length($0);i++) do if (substr($0,i,1) == "r") echo "1" fi done }' |
|
||||
|
Thanks for your reply, but I want it to loop through the string and then perform an action for each occurrance of r, not just once. eg. "rover" would return 11 in this example because there're two r's in it.
I've tried adapting your code so it looks something like this: echo $string | awk '{ for (i=1;i<=length($0);i++) do if [[ (substr($0,i,1) == *r*) ]] ; then echo "1" fi ; done }' but get parse errors all over the place: awk: cmd. line:4: if [[ (substr($0,i,1) == *r*) ]] ; then awk: cmd. line:4: ^ parse error awk: cmd. line:4: if [[ (substr($0,i,1) == *r*) ]] ; then awk: cmd. line:4: ^ parse error awk: cmd. line:4: if [[ (substr($0,i,1) == *r*) ]] ; then awk: cmd. line:4: ^ parse error Any more ideas? |
|
||||
|
Quote:
With due regards, I would like to say that the above may not solve the problem, OP is having. He is looking for no. of occurence of a character in a string. And the above command will give always give output as 1 if there is one or more than one occurence of "r" Kindly correct me if I am wrong Gaurav |
|
|||||
|
Quote:
Good catch. |
![]() |
| Bookmarks |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|