home | list info | list archive | date index | thread index

Re: [OCLUG-Tech] Shell scripting: how to loop through characters of a string?

On 28/07/17 07:15 AM, rpjday [ at ] crashcourse [ dot ] ca wrote:
> 
>   Curious about the best(?) way to do some simple operations in a shell
> script
> that I would *prefer* to be POSIX-compliant, so here's the first
> question --
> how to loop through the individual characters of a string?
> 
>   I just stumbled across this solution I'd never heard of:
> 
>   $ echo "rday" | grep -o .     [-o,--only-matching option to grep]
>   r
>   d
>   a
>   y
>   $
> 
> so, obviously, I can stick that command in a "for" loop in my script.
> I'm not sure I need anything simpler or more elegant than that, but is
> there anything even cooler?
In my head I came up with some other loops like
  echo -n "abcåäöÅÄÖ"|sed 's/./&\n/g'
(don't forget international characters may not be 1 byte)
I then asked google who found
https://stackoverflow.com/questions/10551981/how-to-perform-a-for-loop-on-each-character-in-a-string-in-bash

And there it's several other ways including one I didn't know about
(fold) but interesting enough the grep -o one is not listed there.

/ps

> 
>   More shell questions coming shortly ...
> 
> rday
> 
> 
> _______________________________________________
> Linux mailing list
> Linux [ at ] lists [ dot ] oclug [ dot ] on [ dot ] ca
> http://oclug.on.ca/mailman/listinfo/linux