/usr/bin/perl^M: bad interpreter: No such file or directory

时间:2022-05-22 20:42:41

一个perl脚本,运行后返回/usr/bin/perl^M: bad interpreter: No such file or directory。网上查,说法挺多。有的第一行是#!/usr/bin/perl -w时就出这个问题,改成#!/usr/bin/perl后就没问题的。我的第一行就是#!/usr/bin/perl,改成#!/usr/bin /perl -w,居然就没问题了。奇了怪了。忽然想起3年前在日本使用的solaris9系统服务器时似乎也遇到了同样问题。翻出就日志一看,应该就是 windows与unix文本文件格式不同所致。现摘抄我的旧文如下。当时我用的居然是英文。

Be aware that UNIX text file format is different from Windows system

The UNIX and DOS operating systems (which includes Microsoft Windows) differ in the format in which they store text files. DOS places both a line feed and a carriage return character at the end of each line of a text file, but Unix uses only a line feed character. Some DOS applications need to see carriage return characters at the ends of lines, and may treat Unix-format files as giant single lines. Some Unix applications won't recognize the carriage returns added by DOS, and will display Ctrl-m characters at the end of each line. This appears on the screen as ^M.

On systems using SunOS, the utilities dos2unix and unix2dos are available. These utilities provide a straightforward method for converting files from the Unix command line. To use either command, simply type the command followed by the name the file you wish to convert, and the name of a file which will contain the converted results. Thus, to convert a DOS file to a Unix file, at the Unix prompt, enter: dos2unix dosfile.txt unixfile.txt. To convert a Unix file to DOS, enter: unix2dos unixfile.txt dosfile.txt. Note that these utilities are only available on SunOS systems.

To convert a DOS text file to a Unix text file using Perl, at the Unix shell prompt, enter: perl -p -e 's/\r$//' < dosfile.txt > unixfile.txt. To convert from a Unix text file to a DOS text file with Perl, at the Unix shell prompt, enter: perl -p -e 's/$/\r/' < unixfile.txt > dosfile.txt. Please note that you must use single quotation marks in either command line.  This prevents your shell from trying to evaluate anything inside.

我 想linux是与时俱进的,于是在在bash中输入,which dos2unix,返回/usr/bin/dos2unix,同样unix2dos也有的。哈哈,看来these utilities are not only available on SunOS systems. 不过命令似乎更简单,只需要dos2unix dosfile,结果dosfile自动变成了了unix format的了。运行perl脚本,一切OK!

因此,我的如下修改了:   

从windows的文件格式转换成linux下的文件格式:

perl -p -e 's/\r$//' < dosfile.txt > unixfile.txt

从linux的文件格式转换成windows下的文件格式:

perl -p -e 's/$/\r/' < unixfile.txt > dosfile.txt

OK!