Replacing new line character with a pipe and a new line character

9,162

Solution 1

Unless you have joined lines, the \n doesn't appear in sed's pattern space: the end-of-line anchor is $.

So with GNU sed:

sed -i 's/$/|/' temp.txt

Solution 2

You can use paste:

$ :|paste -d'|' file - > new_file
one|two|three|four|five|
abc|def|pqr|lmn|xyz|

or perl:

perl -i.bak -ple '$_.="|"' file

Solution 3

With GNU sed, you could replace the end of line with | by using:

sed -i 's/$/|/' temp.txt

That will match the end of the line and "replace" it with |, but of course the line will still end and keep its \n

Share:
9,162

Related videos on Youtube

Vicky
Author by

Vicky

A software developer with zeal to learn new things all the time!!

Updated on September 18, 2022

Comments

  • Vicky
    Vicky over 1 year

    I am using ksh.

    I have a file temp.txt with some pipe delimited data.

    one|two|three|four|five
    abc|def|pqr|lmn|xyz
    

    As clear from example, the record ends with a new line character after the data value in the last column.

    However, I want the record to end with a pipe delimiter and a new line character as below:

    one|two|three|four|five|
    abc|def|pqr|lmn|xyz|
    

    I tried the following commands but still unsuccessful:

    tr '\n' '|\n' < temp.txt
    

    and

    sed -i 's/\n/|\n/g' temp.txt
    

    Am I missing something?

  • Vicky
    Vicky about 9 years
    Great. This works. Did not know end-of-line is $ for sed. Thanks!
  • Vicky
    Vicky about 9 years
    Great. This works. Did not know end-of-line is $ for sed. Thanks!
  • heemayl
    heemayl about 9 years
    +1. Could you explain the paste a bit..
  • cuonglm
    cuonglm about 9 years
    @heemayl: : is no-op and it was piped to paste. paste merge lines from file and stdin (which is empty) with | as delimiter.
  • Angel Todorov
    Angel Todorov about 9 years
    hmm, excessively clever for my taste (and I love a dash of clever!). How about paste -d'|' file /dev/null ?
  • Angel Todorov
    Angel Todorov about 9 years
    The $ end-of-line marker is a regular expression feature, not specific to sed.
  • cuonglm
    cuonglm about 9 years
    @glennjackman: It's ok in this case, but can cause long typing when you need multiple /dev/null, something like this.
  • syntaxerror
    syntaxerror almost 9 years
    May I also add that the ignoring of \n (et al) will even apply to their hexadecimal representation! That means in practice, that sed 's/someregex\x0a/something/' will fail as well, because sed will ignore the control character specified in hex in the regex. I had to learn this the hard way back then, when I had to debug the actual cause why my parser did not operate the expected way.