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.
  • 61,009
  • 14
  • 85
  • 115
jonathan
  • 281
  • 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
  • 131,515
  • 23
  • 189
  • 171
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
  • 350,152
  • 45
  • 431
  • 590