开发者

Using sed to convert text file to a C string

开发者 https://www.devze.com 2023-02-21 05:37 出处:网络
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

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 '开发者_如何学Python\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>

  1. s/\\/\\\\/g - escape back slashes
  2. s/"/\\"/g - escape quotes
  3. s/ /\\t/g - convert tabs
  4. s/^/"/ - prepend quote
  5. s/$/\\n"/ - append \n and quote


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


In Perl, file input from stdin, out to stdout. Hexifies, so no worries about escaping stuff. Doesn't remove tabs, etc. Output is a static C string.

use strict;
use warnings;

my @c = <STDIN>;

print "static char* c_str = {\n";
foreach (@c) {
    my @s = split('');
    print qq(\t");
    printf("\\x%02x", ord($_)) foreach @s;
    print qq("\n);
}
print "};\n";
0

精彩评论

暂无评论...
验证码 换一张
取 消