-1

I would like to replace linefeed by something else like #

I have tried sed but \n doesn't work and \x0a as well

I got file z1

cat z1|hd

00000000  30 0a 61 0a 0a 31 0a 62  0a 0a 32 0a 63 0a        |0.a..1.b..2.c.|

and if i try

cat z1|sed $'s/\x30//g' 

everything is fine

But it doesn't work for line feed in sed, just an error message

cat z1|sed $'s/\x0a//g' 

If i try

cat z1| tr "\n" "#"|hd

everything is fine for linefeed

Why is sed not working for linefeed ?

innerjoin
  • 3
  • 4

3 Answers3

1

sed will not match literal newline, because commands in sed are delimetered by a newline. So sed, when parses the command, sees a newline and assumes it is the end of this command. And then sed errors with a syntax error, because s/ is an invalid command, the s needs three delimeter characters, / here. More specifically, posix sed documentation explicitly forbids embedding literal newline in BRE inside s/BRE/replacement/flags command: A literal <newline> shall not be used in the BRE of a context address or in the substitute function.

Outside from that, sed parses the input line after line, but ignores the newline from input and automatically appends a newline when printing. So even if you did s/\n/#/ it wouldn't do anything, because there is no newline in the input. You can: append all the lines into hold space, then switch hold space with pattern space and then substitute newlines. This is the solution presented by @potong.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

There are sed versions which accept \n or hex character codes but this is not portable. If you can't use tr (why not?) then maybe explore Perl, which of course is not standard at all, but available practically everywhere; and because there is only one implementation, it will work everywhere Perl is available.

perl -pe 'y/\n/#/' z1

Also note the absence of a useless cat.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • "Perl is not standard" Do you mean it is not ratified by a governing standards body? – suspectus Aug 20 '19 at 08:22
  • 1
    Yeah, `sed` is standardized in POSIX etc whereas Perl is not. Ironically, the standard does not specify a particular behavior for this specific use case. – tripleee Aug 20 '19 at 08:22
0

This might work for you (GNU sed):

sed '1h;1!H;$!d;x;y/\n/#/' file

This slurps the file into memory, then translate \n's to #'s

Alternative:

sed -z 'y/\n/#/' file
potong
  • 55,640
  • 6
  • 51
  • 83
  • No, the first command should work on all posix compatible `sed`s. The second is only for GNU sed - it supports the `-z` option. – KamilCuk Aug 22 '19 at 00:18