We have 10 PC with some version of Ubuntu and only remote access. While doing some upgrades to custom software I did not notice that the line endings in some scripts were Windows version (CR+LF) and not the Unix version (LF). So now when I want to launch the script it gives an error:

bash: /usr/local/bin/portsee: /usr/bin/python^M: bad interpreter: No such file or directory

Is there a way to change all line endings in a script from terminal. The thing is that I can not install any new software to this group of PC-s.

  • 1
    Use the sed command from the duplicate's accepted answer. – terdon Jul 26 '16 at 15:07

Option 1: dos2unix

You can use the program dos2unix, which is specifically designed for this:

dos2unix file.txt

will replace all CR from all lines, in place operation.

To save the output in a different file:

dos2unix -n file.txt output.txt

You might need to install it first by:

sudo apt-get install dos2unix

Option 2: sed

Or you can use sed to replace all CR (\r) from line endings:

sed -i.bak 's/\r$//' file.txt

With option -i, the file will be edited in-place, and the original file will be backed up as file.txt.bak.

  • 8
    I did use the sed command and it worked. Thank you! – NonStandardModel Jul 26 '16 at 15:14
  • 3
    dos2unix and unix2dos are present in cygwin as well – Obi Wan - PallavJha Jul 23 '19 at 9:00
  • 1
    This answer shows applying dos2unix recursively. Useful when moving a git repo from windows to ubuntu. – Nagabhushan S N Aug 3 '20 at 8:11
  • 1
    sed worked for me but had to supply the global flag as in: sed -i.bak 's/\r$//g' file.txt – Jono Nov 2 '20 at 17:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.