I'm having a hard time reading a file stored in a variable. it should be straightforward but somehow I'm missing something, can't find out what?

while read -r line
  count=`expr $count + 1`
  echo "line $count "   
done < $mip

it's a really basic and simple script which count the number of lines like so, but when I used a variable done < $mip instead of the file name done < fila.txt. the script just outputs the file content like cat fila.txt instead of counting the lines.

line 1
line 2
line 3
line 4
line 5
line 6

any ideas ??

  • Don't read the contents of the file into a variable, just iterate over the file: done < fila.txt – glenn jackman Feb 21 '17 at 17:53

done <$mip still assumes that $mip is a filename. It's not.

What you want is probably something like

printf '%s\n' "$mip" |
while IFS= read -r line; do
   printf 'line %d\n' "$(( ++count ))"

The more straight forward solution is

while IFS= read -r line; do
   printf 'line %d\n' "$(( ++count ))"
done <filea.txt

or even

cat -n filea.txt | sed 's/^ *\([0-9]*\).*$/line \1/'

That last command will use cat for enumerating the lines in the file and sed to delete the actual file contents.

Or, with awk, which is even more straightforward:

awk '{ printf("line %d\n", NR) }' filea.txt

Or, if you count the lines in the file first:

count=$( sed -n '$=' filea.txt )    # or:  count=$( wc -l <filea.txt )
printf 'line %d\n' {1..$count}
  • or while … done <<<"$mip", if it's a non-ancient ksh. – Gilles Feb 20 '17 at 23:34
  • Since you are using a pipe, all changes made to the count variable are done in a subshell, so the variable will only be useful in the loop – glenn jackman Feb 21 '17 at 17:52
  • thanks it worked, and also for all the details it's really helpful to learn from the best, again thank you – Driven Feb 22 '17 at 3:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.