acyang
acyang

Reputation: 13

Use sed to append text at the end of some specific lines

I have a file like this

{CRLF  
sum: 21.46,CRLF  
first: 99.10,CRLF  
last: 57.71 CRLF  
}CRLF  
{CRLF  
sum: 159.32,CRLF  
first: 456.71,CRLF  
last: 89.27 CRLF  
}CRLF  

...

ps. CRLF is the line break in windows system, not really text in this file.

I want to add a comma at the end of every line containing "last:".
I used the following command

sed '/last/ s/$/,/' old.txt >new.txt  

but I got a weird result

{CRLF  
sum: 21.46,CRLF  
first: 99.10,CRLF  
last: 57.71 CR  
,CRLF  
}CRLF  
{CRLF  
sum: 159.32,CRLF  
first: 456.71,CRLF  
last: 89.27 CR  
,CRLF  
}CRLF  
...  

The comma doesn't append at the end of line. Instead, it append at a new line. Any idea will be greatly appreciated. Thanks.

Upvotes: 1

Views: 4254

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

Your data file has DOS-style (Windows-style) CRLF line endings. sed inserts the comma between the CR and the LF (because it doesn't know about CRLF line endings and CR is just another character before the end of line).

Edit your file to remove the DOS line endings: see How to convert DOS/Windows newline to Unix newline in bash script for information on how to do that. Or, as Beta pointed out, you can do that at the same time that you add the comma:

sed -e 's/.$//' -e '/last:/s/$/,/'

This is mildly dangerous if applied to a file with Unix line endings; it will remove the last character on those lines too. It might be better to embed the CR in the script:

sed -e $'s/\r$//' -e '/last:/s/$/,/'

which uses bash's ANSI-C Quoting mechanism to embed a CR into the command string.

You're not completely consistent in your question. You say 'lines containing line:' but your code handles 'lines containing line' (missing out the colon). Your choice.

Upvotes: 1

Related Questions