1

Input:

bharti+bharti-ims+bharti-sdm+RuleForBhartiOnlyIndices+kibana_user

Desired Output:

"bharti","bharti-ims","bharti-sdm","RuleForBhartiOnlyIndices","kibana_user"

Command:

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:

"bharti","bharti-ims","bharti-sdm","RuleForBhartiOnlyIndices","kibana_user

Look at the missing " at the the end.

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

1
2

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
0000007

\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.

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

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
1

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.