I have a file named test.txt and it contains the following:
this is the last
char
another last
char
very last
I have a bash script (script.sh) having the following code:
#!/bin/bash
lastline=0
ctr=0
input="test.txt"
while IFS= read -r line
do
((ctr=ctr+1))
echo "$ctr"
if [ "$line" == "char" ]; then
lastline=$ctr
fi
done < "$input"
echo "$lastline"
My problem are these:
When I run the command
bash script.sh
, I always get the value 0 for the variable lastline. It looks like it doesn't passed the condition even though there's a "char" on the test.txt file.It also seems like the while loop doesn't include the last line. There are 5 lines on the test.txt file, however, when I tried to echo out the variable ctr, the last number printed is only 4.
UPDATE
I've updated the code base on RavinderSingh13 answer. I added tr -d '\r' < test.txt > temp && mv temp test.txt
here's the updated code:
#!/bin/bash
tr -d '\r' < test.txt > temp && mv temp test.txt
lastline=1
ctr=1
input="test.txt"
while IFS= read -r line
do
echo "$line"
if [ "$line" == "char" ]; then
lastline=$ctr
fi
((ctr=ctr+1))
done < "$input"
echo "$lastline"
I definitely did see some weird characters (^M) at the end of each line when I ran the command cat -v test.txt
, so I added RavinderSingh13 answer to remove them. However, it still doesn't retrieve the last line. If ever, the string on the last line is "char" then the result will be wrong. The picture below shows that the loop ends on the 4th line. The expected result should be 1 2 3 4 5 4. That's why if the "char" text is found on the last line, the result will be wrong since it didn't evaluated the last text on the last line.