Search code examples
perlechoeol

EOL with perl -p -e


Let's start with this:

echo "1 2 3 4 5 6" | perl -pe 's/ /\n/g'   > unix.txt
echo "1 2 3 4 5 6" | perl -pe 's/ /\r\n/g' > dos.txt
echo "1 2 3 4 5 6" | perl -pe 's/ /\r/g'   > mac.txt

When I open the dos file with vim I get the annoying ^M and vim doesn't recognize the dos file as a dos format even with set ffs=unix,dos,mac.

Thus I investigated a bit further:

$ hexdump -C unix.txt
00000000  31 0a 32 0a 33 0a 34 0a  35 0a 36 0a              |1.2.3.4.5.6.|

$ hexdump -C dos.txt
00000000  31 0d 0a 32 0d 0a 33 0d  0a 34 0d 0a 35 0d 0a 36  |1..2..3..4..5..6|
00000010  0a                                                |.|

$ hexdump -C mac.txt
00000000  31 0d 32 0d 33 0d 34 0d  35 0d 36 0a              |1.2.3.4.5.6.|

I notice that a 0a appears at the end of each file. I don't understand why. How to get rid of it?


Solution

  • echo  "1 2 3 4 5 6" | hexdump -C
    00000000  31 20 32 20 33 20 34 20  35 20 36 0a              |1 2 3 4 5 6.|
    --------------------------------------------^^
    
    echo -n "1 2 3 4 5 6" | hexdump -C
    00000000  31 20 32 20 33 20 34 20  35 20 36                 |1 2 3 4 5 6|
    

    From man echo

    -n     do not output the trailing newline