Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to read line by line from file in bash script?

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?

like image 340
jonathan Avatar asked Dec 04 '22 19:12

jonathan


1 Answers

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
like image 119
Michael Krelin - hacker Avatar answered Dec 15 '22 11:12

Michael Krelin - hacker