Why sed command deletes last line in a file if no carriage return?

Hi

I am using sed command to make SCORE=somevalue to SCORE=blank in a file.

Please see the attached lastline.txt file. After executing the below command on the file, it removes the last line.

cat lastline.txt | sed 's/SCORE=.*$/SCORE=/g' > newfile.txt

Why does sed command remove the last line in the file if there is no carriage return?

Also if i use echo [\\r](file://\\r) >> lastline.txt and then execute the command it works fine and the last line is not removed.

Also, How to check if the last line already has a carriage return or not ? and add if there is no carriage return?

Input File : lastline.txt

[KEY A]
TABLE=TableA
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreA
[KEY B]
TABLE=TableB
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreB
[KEY C]
TABLE=TableC
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreC
[KEY D]
TABLE=TableD
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreD
[KEY E]
TABLE=TableB
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreB
[KEY F]
TABLE=TableF
KEY=KEYF
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreF
[KEY G]
TABLE=TableA
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreG
[KEY H]
TABLE=TableB
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreH
[KEY I]
TABLE=TableA
KEY=KEYA
DESC=VALUE
ORDERBY=Id
SCORE=C:\Common\TestscoreI

Please note that there should not be any blank line at the bottom of input file. No carriage return on the last line.

Thanks
Ashok

Have a read of this post:

http://www.unix.com/shell-programming-scripting/57511-sed-skipping-last-line-file.html\#5

This is Useless Use of Cat:

cat lastline.txt | sed 's/SCORE=.*$/SCORE=/g' > newfile.txt

This should be sufficient:

sed 's/SCORE=.*$/SCORE=/g' lastline.txt > newfile.txt
1 Like

Hi,

How to check if the last line in a file has ended with carriage return or not?

How to check this in shell script and and add new line programatically?

Thanks
Ashok

One way could be something like this:

file="lastline.txt"

lastchar=$(od -An -t dC $file |awk 'NF{c=$NF}END{print c}')
if [ $lastchar = "10" ]
then
  echo "file is OK"
else
  echo >> $file
fi
1 Like