How to Add a Carriage Return as a Character to a File

How to add a carriage return as a character to a file?

If you're using vim you can enter insert mode and type 'CTRL-v CTRL-m'. That ^M is the keyboard equivalent to \r. (see Insert the carriage return character in vim)

Inserting 0x0D in a hex editor will do the task.

Carriage return character in files

When printing to a console window (i.e. not a file) the \r instructs it to go back to the beginning of a line (hence your "Character is" text disappears). The \n, however, instructs it to go the next line. The \r is useful for showing progress on the same line, for example.

Files can be saved with either \r\n, \n, or a \r at the end of each line (see comment below), and these days are interpreted the same by text-editors (in fact many warn you if you mix the types within a file). It would appear you have one file with \r\n and the other with just \n in.

Insert the carriage return character in Vim

Type: ctrl-v ctrl-m

On Windows Use: ctrl-q ctrl-m

Ctrl-V tells vi that the next character typed should be inserted literally and ctrl-m is the keystroke for a carriage return.

Separating large file and inserting carriage returns based on string

Since your lines are very big, you'll have to:

  • Read/Write one character at a time
  • Save the last x characters
  • If the last x characters are equal to your term, write a new line

    Dim term As String = "</ext>"
    Dim lastChars As String = "".PadRight(term.Length)

    Using sw As StreamWriter = New StreamWriter("C:\My Documents\output.txt")
    Using sr As New System.IO.StreamReader("C:\My Documents\input.txt")
    While Not sr.EndOfStream
    Dim buffer(1) As Char
    sr.Read(buffer, 0, 1)

    lastChars &= buffer(0)
    lastChars = lastChars.Remove(0, 1)

    sw.Write(buffer(0))

    If lastChars = term Then
    sw.Write(Environment.NewLine)
    End If

    End While
    End Using
    End Using

Note: This will not work with a Unicode file. This assume each characters are one byte.

Create file with Carriage Return character in filename

On OSX:

#!/bin/sh
CR=$(echo X |tr X '\r')
ls >"foo${CR}bar"

makes a file that ls would show as foo?bar, where the ? is an ASCII carriage return.

How to insert a new line character after a fixed number of characters in a file

How about something like this? Change 20 is the number of characters before the newline, and temp.text is the file to replace in..

sed -e "s/.\{20\}/&\n/g" < temp.txt


Related Topics



Leave a reply



Submit