Sometimes you may need, for example for unit-tests, to hard-code text in you java classes.
The following sed command can help you:
sed 's/"/\\"/g; s/^/"/; s/$/\\n"+/; $ s/\\n"+/";/' filename
It performs respectively this tasks:
- Replace all occurencies of " with \"
- Insert " at the begininng of each line
- Insert \n"+ at the end of each line
- Replace the last occurency of \n"+ with ";
For example:
A woman's face with nature's own hand painted,
Hast thou, the master mistress of my passion;
A woman's gentle heart, but not acquainted
With shifting change, as is false women's fashion:
An eye more bright than theirs, less false in rolling,
Gilding the object whereupon it gazeth;
A man in hue all hues in his controlling,
Which steals men's eyes and women's souls amazeth.
And for a woman wert thou first created;
Till Nature, as she wrought thee, fell a-doting,
And by addition me of thee defeated,
By adding one thing to my purpose nothing.
But since she prick'd thee out for women's pleasure,
Mine be thy love and thy love's use their treasure.
will be:
"A woman's face with nature's own hand painted,\n"+
"Hast thou, the master mistress of my passion;\n"+
"A woman's gentle heart, but not acquainted\n"+
"With shifting change, as is false women's fashion:\n"+
"An eye more bright than theirs, less false in rolling,\n"+
"Gilding the object \"whereupon\" it gazeth;\n"+
"A man in hue all hues in his controlling,\n"+
"Which steals men's eyes and women's souls amazeth.\n"+
"And for a woman wert thou \"first\" created;\n"+
"Till Nature, as she wrought thee, fell a-doting,\n"+
"And by addition me of thee defeated,\n"+
"By adding one thing to my purpose nothing.\n"+
"But since she prick'd thee out for women's pleasure,\n"+
"Mine be thy love and thy love's use their treasure.";
A very goldmine of "cooking tips" on sed can be found
here
To distribute a long string across multiple lines:
fmt [filename] | sed 's/"/\\"/g; s/^/"/; s/$/\ " +/; $ s/\ " +/"/'