3

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!

sasha.sochka
  • 14,395
  • 10
  • 44
  • 68
vista_narvas
  • 31
  • 1
  • 2

2 Answers2

4

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
gniourf_gniourf
  • 44,650
  • 9
  • 93
  • 104
2

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.

James Holderness
  • 22,721
  • 2
  • 40
  • 52
  • Doesn't that fail whenever the input-file contains whitespace? – ruakh Jun 30 '13 at 22:52
  • @ruakh Nope. I checked with spaces and it worked fine. Note that the `$char` in the eval isn't expanded until the actual assignment is evaluated, because there is a backslash before the dollar. – James Holderness Jun 30 '13 at 23:17
  • @JamesHolderness: Yeah, I noted it, but . . . oh, I see. I always forget that word-splitting doesn't take place on the right-hand-side of an assignment. – ruakh Jun 30 '13 at 23:24