in reply to Problem with String replace in file

| is a special character for regexs. It needs to be escaped.

s/\|\|/|\\N|/;

However, that solution is far from complete.
What if the first field is empty?
What if the last field is empty?
What if there's more than one empty fields?
What if there's more than one empty fields in a row?
Fix:

s/\|(?=\|)/|\\N/g; s/^\|/\\N|/; s/\|$/|\\N/;

As a one-liner:

perl -pe"s/\|(?=\|)/|\\N/g; s/^\|/\\N|/; s/\|$/|\\N/" infile >outfile

Replies are listed 'Best First'.
Re^2: Problem with String replace in file
by philosophia (Sexton) on Oct 22, 2007 at 17:36 UTC
    if I use

    s/\|(?=\|)/|\\N/g; s/^\|/\\N|/; s/\|$/|\\N/g;

    it replaces || with ||. The \N seems to be an invisible newline character, and I want it to just be '\N'.