Question

I'm using shell script and I want to add a space at the end of the line if the last characters are: ,.-

I've tried sed 's/,.-\r\n/,.- \r\n/g' part2.out > part3.out but it didn't work, what am I missing?

Was it helpful?

Solution

Use $ to match the end of line, and escape the .:

sed 's/,\.-$/,.- /'

You should probably use & as well, and you might prefer to only do the replacement if the line matches:

sed '/,\.-$/s//& /'

Since your lines appear to have DOS line endings, you might want to take care of them with dos2unix or some other utility more suited to that. One simple (but not robust) solution is to just delete the \r characters, since you almost certainly do not actually want them in the data:

tr -d \\r < part2.out | sed 's/,\.-$/& /' > part3.out

is probably good enough. If Jaypal is correct and you are trying to match any line that ends in any of the characters ,, ., or - instead of ending with the string ,.-, then you want:

sed 's/[,.-]$/& /'

OTHER TIPS

This should work -

sed 's/\([\.,-]\)$/\1 /g' input_file

Test: cat -vet will show you special non printing characters

$ cat -vet ff
col1a col2a col3a col4a col5a col6a XXXXXXAAAAA col8a ...$
col1b col2b col3b col4b col5b col6b XXXXXXBBBBB col8b ..-$
col1c col2c col3c col4c col5c col6c XXXXXXCCCCC col8c ..,$
col1d col2d col3d col4d col5d col6d XXXXXXDDDDD col8d ...$

$ sed 's/\([\.,-]\)$/\1 /g' ff | cat -vet
col1a col2a col3a col4a col5a col6a XXXXXXAAAAA col8a ... $
col1b col2b col3b col4b col5b col6b XXXXXXBBBBB col8b ..- $
col1c col2c col3c col4c col5c col6c XXXXXXCCCCC col8c .., $
col1d col2d col3d col4d col5d col6d XXXXXXDDDDD col8d ... $

If you have CR+LF line endings, you can try:

sed '/[.,-]\r/ {s/\r/ A/}'

(use $ instead of \r in case of LF as the newline character)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top