8

I have text file which shows ^M character when opened using less command in mac terminal. I tried using the below command to remove ^M character.

awk '{ gsub("\n", "\r"); print $0;}' input > output
cat input | tr ‘\n’ ‘\r’ > output

But none of them worked. Could someone help to fix this using some Linux commands.

Kara
  • 6,115
  • 16
  • 50
  • 57
chas
  • 1,565
  • 5
  • 26
  • 54
  • cannot install in mac – chas Feb 25 '14 at 20:00
  • 2
    The answers below tell you how to remove `^M`s as you requested, but they're wrong if you actually only want to remove the `^M` that appears at the end of a line for files with DOS line endings since they'll remove either the first `^M` or all `^M`s instead of just one that appears at the end of a line. To handle those correctly see [https://stackoverflow.com/questions/45772525/why-does-my-tool-output-overwrite-itself-and-how-do-i-fix-it](https://stackoverflow.com/questions/45772525/why-does-my-tool-output-overwrite-itself-and-how-do-i-fix-it). – Ed Morton Nov 11 '21 at 17:09

3 Answers3

5

You can use sed:

 sed 's/^M//' filename > newfilename

If you wish to use awk then do:

awk '{sub(/^M/,"")}1' filename > newfilename

To enter ^M, type CTRL-V, then CTRL-M. That is, hold down the CTRL key then press V and M in succession.

Update

As suggested by @glenn jackman in comments, it is easy to use \r then to get ^M

Dima Lituiev
  • 12,544
  • 10
  • 41
  • 58
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
2
col < input > output

Or:

vim "+set ff=unix" "+saveas output" "+q" input
Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521
1

use the octal value from http://www.asciitable.com/

echo "1'2^M34" | awk 'gsub(/\015/,":")' 1'2:34

Henry Barber
  • 123
  • 1
  • 5