Score:0

Reading Files with LOOP in Bash Script?

ad flag

I hope someone can explain to me what's happening in this situation and how to solve it.

I am trying a simple thing: to read each row from a text file with loop.

This is the text file content that I am working on:

aaaa   aaaa a aa
bb bbbbb bbbbb    b
cccccccc          c                              c      c

NOTE: This is a simple file, just to test the concept. The main text file I am working have around 140MB, with a positional layout for each field.

This is my bash script content:

FILE=./text.txt

awk '{ print }' $FILE | while read ROW; do
    echo $ROW
done

I am getting each row from the file, but this is the result:

aaaa aaaa a aa
bb bbbbb bbbbb b
cccccccc c c c

As you can see, the extra white spaces are being remove from the ouput.

I am trying to test this script using awk, but I already tried with cat and stdout and had the same result:

FILE=./text.txt

# cat
cat $FILE | while read ROW; do
    echo $ROW
done

##########

# stdout
while read ROW; do
    echo $ROW
done < $FILE

I also tried using for loop:

for ROW in $(awk '{ print }' $FILE); do
    echo $ROW
    echo "---"
done

But this was the result, each row content was split by the white spaces:

aaaa
---
aaaa
---
a
---
aa
---
bb
---
bbbbb
---
bbbbb
---
b
---
cccccccc
---
c
---
c
---
c
---

As I mentioned before, the main text file have positional fields, that's why I need all row characters, even if they are extra white spaces.

I was wondering if someone can explain to me why the extra white spaces were removed and how to print/work row full content (with any extra white space)?

hr flag
`echo $ROW` should be `echo "$ROW"`- see [bash - When is double-quoting necessary?](https://unix.stackexchange.com/a/68748/65304). Also you likely want `IFS= read -r ROW` rather than just `read ROW`.
jpbrain avatar
ca flag
That's the answer ^^^^^^^^ (steeldriver). Arguments are different with quotes.
Leandro Mana avatar
ad flag
Thanks a lot guys for the help!!! It worked =D. I will pay attention to quotes from now on. Thanks again
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.