Compare array index number against element in bash
Hi.
Consider this snippet of code in bash: Code:
shopt -sq nocasematch Is this possible, and if so, how could I achieve this? I hope my attempt at an explanation makes sense :) Cheers! |
Quote:
The following makes no sense to me: Quote:
You then mention about a third array, so maybe you could explain the big picture as your current solution may not necessarily be the best. |
How about
Code:
#!/bin/bash |
Recursive version, to test it run it and type away, or send it input via a pipe:
Code:
me@localhost:~$echo "apple" | thescript Code:
#!/bin/bash Eventually, an instance of match_idx will obtain a $first containing the last character of $line and $rest will be empty. It will echo the position and make a final call to itself with an empty argument. The instance of match_idxs called with an empty argument will return without calling itself again, thus provoking the return of all previous instances of match_idxs in "chain reaction", up to the very first. At that point $line will be processed entirely and the original instance of match_idxs will return to the main "while" loop. |
Ingeniously neat, Juako :)
|
Not sure we had to use extra functions:
Code:
#!/bin/bash |
A slightly different solution, using an associative array.
Code:
#!/bin/bash |
Quote:
In all fairness, regardless of how recursion provides (IMO) for more compact and beautiful code, I have to say that (in Bash) it is more expensive than iteration, mostly because Bash lacks tail call optimization, which means overhead and chances of stack overflows if you are processing a too large input (ie: you'll have to spawn an entire bash process PER CHARACTER you are examining!!). So, I have to recommend a loop unless you know you want to afford the extra cost. In that sense grail's snippet is preferable, definitely. |
Thank you very much for all your examples, guys! They all achive exactly what I was looking for. I'll study your code and see how I can get some inspiration from the ideas provided here. Extra kudos to you, David the H., for the associative array example and for commenting your code properly, very helpful. :)
|
Glad to help. It's a good idea to always clearly comment your code.
By the way, if it's possible for the input string to contain characters not defined in the assoc. array, you can tell it to output a default value with the pattern "${var:-default}". To have it insert an asterisk, for example, for each unsupported value, simply modify the output loop thus: Code:
for i in "${input[@]^^}"; do |
@rewtnull & David the H.
I acknowledge your remarks on commenting code, after all this is a site for learning. Won't be of much help if I post code (no matter what length) and assume everyone will read it like it's english. Sorry, I'll take it into account for future posts, and add the comments to my entry. |
All times are GMT -5. The time now is 08:49 AM. |