vista_narvas
vista_narvas

Reputation: 31

bash: reading text from a string one character at a time

i have a script to read a file one character at the time this is the script i use

INPUT=/path/
while IFS= read -r -n1 char; do
    echo $char
done < "$INPUT"

it works fine only i cant find out how to store every character into a variable im looking for something like

N$X=$char

where X=the count or characters and $char=the character

Any help would be appreciated. Thanks!

Upvotes: 3

Views: 5903

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46813

As a general thing, having variables like N1, N2, etc... in and hoping to access them like N$i with i another variable is very bad. The cure for this lies in arrays. Here's how I would solve your problem using arrays instead:

n=()
i=0
while read -r -n1 n[i]; do
    echo "Character $i is ${n[i]}"
    ((++i))
done < "$INPUT"

At this point, you have your characters in the array n (well, not all of them). You can have access to character k+1 with

${n[k]}

(remember that array indexes start from 0).


Another possibility is to slurp everything in a string, it's as simple as this:

string=$( < "$INPUT" )

and you can have access to character k+1 with

${n:k:1}

(taking the substring of length 1 starting at index k). Looping on all characters could be done as:

for ((k=0;k<${#string};++k)); do
    echo "Character $k is '${string:k:1}'"
done

Upvotes: 4

James Holderness
James Holderness

Reputation: 23001

You could do something like this:

X=0
while IFS= read -r -n1 char; do
    eval "N$X=\$char"
    X=`expr $X + 1`
done < "$INPUT"

At the end of the loop, X0, X1, X2, etc. will contain the various characters that have been read in.

Upvotes: 2

Related Questions