Desired Output:



echo "bharti+bharti-ims+bharti-sdm+RuleForBhartiOnlyIndices+kibana_user" | sed -e 's/^/"/g' -e 's/+/","/g' -e 's/$/\"/g'

This is working fine and am getting the desired output where the line terminator is LF. As soon as i edit the file in windows and save it the line terminator LF is replaced by CRLF. And the last sed expression where i replace end of line $ with " is failing and getting unexpected result. Unexpected Result:


Look at the missing " at the the end.

Any sed experts out there who can come for my rescue please :).


The quote is actually there, but it has replaced the initial quote when printing to screen:

$ printf '%s\r\n' 'foo' | sed -e 's/^/"/g' -e 's/+/","/g' -e 's/$/\"/g' | od --format c
0000000   "   f   o   o  \r   "  \n

\r/CR/carriage return, moves the position of the virtual cursor used to output text to the start of the line, so the final " ends up overwriting (in the terminal only) the first quote.

You may want to send the input through dos2unix first, unless you're willing to add sed expressions to handle \r.

  • Thank you, i couldn't think of the dos2unix utility. – Sathish Prakasam Mar 16 '20 at 6:01

You can refine the sed expression to eliminate the \r in case it's there:

sed -e 's/^/"/' -e 's/+/","/g' -e 's/\r*$/"/' file

As begin-of-line and end-of line exist just once in a line, the g flag can be dropped. No need to escape the double quotes in the "replacement". Use "alternation" to further simplify:

sed -e 's/^\|\r*$/"/g' -e 's/+/","/g' file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.