I would like to use sed to replace newlines, tabs, quotes and backslashes in a text file to use it as char constant in C, but I'm lost at the start. It would be nice to maintain the newlines also in the output, adding a '\n', then a double quote to close the text line, a crlf, and another double quote to reopen the line, for example:
line1
line2
would become
"line1\n"
"line2\n"
Can anybody at least point me in the right direction? Thanks
Try this as a sed
command file:
s/\\/\\\\/g
s/"/\\"/g
s/ /\\t/g
s/^/"/
s/$/\\n"/
NB: there's an embedded tab in the third line, if using vi
insert by pressing ^v <tab>
s/\\/\\\\/g
- escape back slashess/"/\\"/g
- escape quotess/ /\\t/g
- convert tabss/^/"/
- prepend quotes/$/\\n"/
- append \n and quoteBetter still:
'"'`printf %s "$your_text" | sed -n -e 'H;$!b' -e 'x;s/\\/\\\\/g;s/"/\\"/g;s/ /\\t/g;s/^\n//;s/\n/\\n" \n "/g;p'`'"'
Unlike the one above, this handles newlines correctly as well. I'd just about call it a one-liner.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With