4

I've searched online about this problem and I've found two ways so far:

   while read line; do
      commands
   done < "$filename"

and

    for $line in $(cat $filename); do
       commands
    done

none of these work if the lines have a space though, for example if we have a line like that

  textextext text

it won't print textextext text

but

  textextext
  text

it counts these things as a different line, how can I avoid this to happen?

A.H.
  • 63,967
  • 15
  • 92
  • 126
jonathan
  • 291
  • 1
  • 5
  • 17
  • Are you interested a) in leading and trailing whitespace or b) in intermediate whitespace (e.g. multiple spaces) or c) only in the words in one line? – A.H. Oct 31 '11 at 18:01

2 Answers2

9

Like this?

while IFS= read line ; do
   something "$line"
done <"$file"

Here is a brief test:

while IFS= read line ; do echo "$line"; done <<<"$(echo -e "a b\nc d")"
a b
c d
Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
7

You can you readarray (bash 4+)

readarray lines < "$file"

then

for line in "${lines[@]}"; 
do
    echo "$line"
done

Note that by default readarray will even include the line-end character for each line

sehe
  • 374,641
  • 47
  • 450
  • 633