Taking It One Character at a Time
Problem
You have some parsing to do and for whatever reason nothing else will do—you need to take your strings apart one character at a time.
Solution
The substring function for variables will let you take things apart and another feature tells you how long a string is:
#!/usr/bin/env bash # cookbook filename: onebyone # # parsing input one character at a time while read ALINE do for ((i=0; i < ${#ALINE}; i++)) do ACHAR=${ALINE:i:1} # do something here, e.g. echo $ACHAR echo $ACHAR done done
Discussion
The read
will take input from
standard in and put it, a line at a time, into the variable $ALINE
. Since there are no other variables on
the read
command, it takes the entire
line and doesn’t divvy it up.
The for
loop will loop once for
each character in the $ALINE
variable. We can compute how many times to loop by using ${#ALINE}
, which returns the length of the
contents of $ALINE
.
Each time through the loop we assign ACHAR
the value of the one-character substring
of ALINE
that begins at the ith
position. That’s simple enough. Now, what was it you needed to parse
this way?
See Also
Check out the other parsing techniques in this chapter to see if you can avoid working at this low level
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.