dig_123
dig_123

Reputation: 2378

sed -e 's/^M/d' not working

A very common problem, but I am unable to work around it with sed.

I have a script file ( a batch of commands) say myfile.txt to be executed at once to create a list. Now when I am executing a batch operation my command line interface clearly shows its unable to parse the command as a line feed ^M is adding up at end of each line.

I thought sed to be the best way to go about it.I tried:

    sed -e 's/^M/d' myfile.txt > myfile1.txt
    mv myfile1.txt myfile.txt

It didn't work. I also tried this and it didn't work:

    sed -e 's/^M//g' myfile.txt > myfile1.txt
    mv myfile1.txt myfile.txt

Then I thought may be sed is taking it as a M character in the beginning of line, and hence no result. So I tried:

    sed -e 's/\^M//g' myfile.txt > myfile1.txt
    mv myfile1.txt myfile.txt

But no change. Is there a basic mistake I am doing ? Kindly advise as I am bad at sed.

I found a resolution though which was to open the file in vi editor and in command mode execute this:

    :set fileformat=unix
    :w

But I want it in sed as well.

Upvotes: 4

Views: 13725

Answers (3)

Sacx
Sacx

Reputation: 6392

^M is not literally ^M. Replace ^M with \r. You can use the same representation for tr; these two commands both remove carriage returns:

tr -d '\r'  < input.txt > output.txt
sed -e 's/\r//g' input.txt > output.txt

Upvotes: 12

assenls
assenls

Reputation: 11

Late, but here for posterity: sed Delete / Remove ^M Carriage Return (Line Feed / CRLF) on Linux or Unix

The gist, which answers the above question: to get ^M type CTRL+V followed by CTRL+M i.e. don’t just type the carat symbol and a capital M. It will not work

Upvotes: 1

alinsoar
alinsoar

Reputation: 15803

sed -e 's/^M/d' myfile.txt

Has the following meaning [the same for /\^M/ ]: If the first letter of the line is M, then remove the line, else print it and pass to next.. And you have to insert 2 separators /old/new/ in s[earch command].

This may help you.

Upvotes: 1

Related Questions