Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

unix

sed

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.

like image 775
dig_123 Avatar asked Dec 11 '22 20:12

dig_123


2 Answers

^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
like image 126
Sacx Avatar answered Jan 06 '23 23:01

Sacx


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.

like image 42
alinsoar Avatar answered Jan 06 '23 21:01

alinsoar