Search code examples
windowsmacosscriptingnewlinecarriage-return

Mac versus Windows: End of line and carriage return


This a question about getting Macs and Windows PCs to play nicely with each other.

SCENARIO: I use a Mac. I have a bunch of data files that need some slicing and dicing to use with a visualization toolkit. The visualization software is for Windows only, which is no problem since I have a virtual Windows machine. awk was my tool of choice for this problem, and it generated the input files beautifully. Unfortunately, when I generate the input files for the visualization tool and send them over to the PC, there are no new lines; i.e., on the Mac I open (say) output001.txt:

header.info

# file automatically generated by awk

BEGIN File
...
<columns of data>
...
END File

Looks great, but then I open in on the PC and have:

header.info# file automatically generated by awkBEGIN File...<columns of data>...END File

I understand that Windows and Mac OS treat end of line characters differently. I've read that \n on a Mac stands for newline AND character return whereas Windows treats them separately, necessitating \n\r. But here, the problem is somewhat different. I never used a \n character generating the text file -- awk did all the newlines. Is there a character that I can have awk put at the end of each line it writes so that Windows will understand where the newlines go?


Solution

  • Sure, make the "Output Record Separator" a Carriage Return plus Linefeed. So instead of

    seq 1 10 | awk '1' | cat -vet
    1$
    2$
    3$
    4$
    5$
    6$
    7$
    8$
    9$
    10$
    

    use

    seq 1 10 | awk '1' ORS='\r\n' | cat -vet
    1^M$
    2^M$
    3^M$
    4^M$
    5^M$
    6^M$
    7^M$
    8^M$
    9^M$
    10^M$
    

    Notes:

    seq 1 10 just generates the numbers from 1 to 10.

    1 amounts to true in awk which means it should just do its default thing - which means to just print the current line.

    I just use cat -vet to show the Carriage Returns, i.e ^M.