天天看点

Linux下处理BOM头和^M的简单方法

linux在网络服务器、嵌入式设备的市场上占有较大份额,microsoft windows在桌面操作系统上占有较大的份额,因此有很多的人喜欢用windows去控制操作linux。

既然用windows去控制linux,难免导致windows系统上的产生的文件以某种途径传到了linux系统中,因而导致显示问题或者出现乱码的情况。

例如用windows自带的“记事本”(notepad)程序默认保存的文件会在每一行的结尾处带有^m标记。

ps: 一些常见的错误例子:有的人可能有疑问,为什么我用记事本把文件保存成utf-8也不好用。还有的人在执行“sed -i '/^$/d' filename”时发现明明有空格却没有删除。

因此在日常使用过程中,无论是用什么工具编辑文件上传到linux服务器,都需要注意换行符问题。

现象:

1.cat程序显示有问题

  如文件的开头显示“?t”

2.bash、python等文件执行时报错

  如-bash: ./someshname.sh: /bin/bash^m: bad interpreter: no such file or directory

  但是这种情况如果不想转换换行符,可以直接用相应的解释器去执行这个文件,如

1

<code>/bin/bash</code> <code>.</code><code>/someshname</code><code>.sh</code>

3.其他应用程序如php、java等运行时报错

解释:

换行符(newline、line ending、end of line(eol)或line break),是一种控制字符,用于区分表示每一行的结束。换行符通常由line feed (lf)和carriage return (cr)两者中的一种或者它们的组合出现在计算机系统中,常见的换行符有三种:

lf (unix and os x \n)

cr (classic mac \r)

crlf(windows \r\n)

lf是line feed的缩写,cr是carriage return的缩写,他们的控制字符(\r,\n还是\r\n)由对应的anscii表示。

之所以出现“^m ”是因为^m在anscii中就表示carriage return即\r所以如果在linux的某个打印输出中出现了^m,表示换行符是windows格式的。

bom是byte order mark的缩写,释义为“字节顺序标记”,用于明确表明此文件属于unicode编码,其他的一些作用可以参考维基百科的英文页面(显然中文页面解释的不全面)。

解决办法:

这个问题其实简单到没有必要用一篇文章的篇幅来表述,简答说就一句话:可以借助dos2unix 工具,将windows格式的文本文件转化成linux下可用的格式。但为了方便那些需要详细了解的人,特地多写几句如下。

# remove bom and ^m (bom and ^m can come from windows notepad program and save as 'ansi' or 'utf-8')    

# such as "example^m$", ansi, ascii text, with crlf line terminators     

# such as "m-om-;m-?example^m$", utf-8, utf-8 unicode (with bom) text, with crlf line terminators     

# linux right format is "example$", ascii text     

# other method is using vim [noeol][dos] :set ff=unix

# determine file type  

<code>file</code> <code>testfilename</code>

# display $ at end of each line, display tab characters as ^i, use ^ and m- notation, except for lfd and tabo  

<code>cat</code> <code>-a testfilename</code>

#text file format converters. convert text files with dos or mac line endings to unix line endings and vice versa.   

# debian &amp; ubuntu: apt-get install dos2unix     

# rhel &amp; centos: yum install dos2unix

# dos/mac to unix and vice versa text file format converter   

<code>dos2unix testfilename</code>

关于显示乱码问题

1.有可能跟终端(ssh连接工具)有关系,尝试调整字符编码为utf-8

2.有可能是系统原因,如缺少中文支持

一些可用的参考:

tag:bad interpreter,移除bom,dos2unix命令,crlf,linux换行符

--end--