在Linux/mac下使用vi来查看一些在Windows下创建的文本文件,有时会发现在行尾有一些“^M”。有几种方法可以处理。
一,mac下可以用perl:$perl -pi -e 's/\r\n?//g' part-00000 #将\r替换为\n
perl - pretty obvious, runs the Perl interpreter
-p - says to perl, 'for every line in the file, do this...'
-i - says to perl 'send output back to the same file you read from'
-e - says 'run the next bit as if it's a script'
s/\r/\n/g : This is the bit that does the work
s// - the substitute command, The '/' are just separators
\r - a 'return'
\n - a 'newline
g - means 'global', ie for every ocurrance.
-p - says to perl, 'for every line in the file, do this...'
-i - says to perl 'send output back to the same file you read from'
-e - says 'run the next bit as if it's a script'
s/\r/\n/g : This is the bit that does the work
s// - the substitute command, The '/' are just separators
\r - a 'return'
\n - a 'newline
g - means 'global', ie for every ocurrance.
批量处理
#!/bin/sh
for filename in filefolder/*
do
echo $filename
#perl -pi -e 's/rn?/n/g' "$filename"
perl -pi -e 's/rn?//g' "$filename" #将^M换成空字符串
done
二, linux/mac
1.使用dos2unix命令。
$ dos2unix myfile.txt 亲测不好使 (dos2unix install: http://macappstore.org/dos2unix/)
上面的命令会去掉行尾的^M。
2.使用vi的替换功能。启动vi,进入命令模式,输入以下命令:
:%s/^M$//g # 去掉行尾的^M。
:%s/^M//g # 去掉所有的^M。
:%s/^M/[ctrl-v]+[enter]/g # 将^M替换成回车。
:%s/^M/\r/g # 将^M替换成回车。
3.使用sed命令。和vi的用法相似:
$ sed -e ‘s/^M/\n/g’ myfile.txt # 将^M替换成回车。
sed -e ‘s/^M//g’ myfile.txt #去掉^M
注意:这里的“^M”要使用“CTRL-V CTRL-M”生成,而不是直接键入“^M”。