mllamazares
mllamazares

Reputation: 8196

Why the variable is cut while reading a file?

This is my code to read a file line by line:

IFS=$'\n'
myfile="$1"
i=0
while read line; do
    echo "Line # $i: '$line'"
    let i++
done < "$myfile"

This is the file passed as parameter

Hello
stack
overflow
friends

I execute it like this: test.sh input.txt and I get this result:

'ine # 0: 'Hello
'ine # 1: 'stack
'ine # 2: 'overflow
'ine # 3: 'friends

As you see, The fisrt character is replaced by a quote. And the quote of the final of the line does not appear. Whats going on here? I can't see the mistake? Any idea?

Upvotes: 3

Views: 79

Answers (1)

anubhava
anubhava

Reputation: 785651

Most likely you have \r before end of line in your input file.

You can test same by using:

cat -vte file

This will show ^M$ in the end of file has dos carriage return \r.

You can use this script to read your file correctly:

i=1
while IFS=$'\r' read -r line; do
   echo "Line # $i: '$line'"
   let i++
done < "$myfile"

OR else convert your file into unix file using:

dos2unix file

OR If you don't wish to actually save the file stripped off of \r, you can also use:

while read line; do
........# your code as-is
done < <( tr -d '\r' < "$myfile")

Upvotes: 5

Related Questions