如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
如何以编程方式(不使用vi)将DOS/Windows换行符转换为Unix换行符?
dos2unix和unix2dos命令在某些系统上不可用。 如何使用sed、awk和tr等命令模拟它们?
当前回答
我根据接受的答案做了一个脚本,所以你可以直接转换它,而不需要一个额外的文件,然后删除和重命名。
convert-crlf-to-lf() {
file="$1"
tr -d '\015' <"$file" >"$file"2
rm -rf "$file"
mv "$file"2 "$file"
}
只要确保你有一个像“file1.txt”这样的文件,“file1.txt”。Txt2”不存在,否则将被覆盖。我将此作为存储文件的临时位置。
其他回答
如果您没有访问dos2unix的权限,但是可以阅读这个页面,那么您可以从这里复制/粘贴dos2unix.py。
#!/usr/bin/env python
"""\
convert dos linefeeds (crlf) to unix (lf)
usage: dos2unix.py <input> <output>
"""
import sys
if len(sys.argv[1:]) != 2:
sys.exit(__doc__)
content = ''
outsize = 0
with open(sys.argv[1], 'rb') as infile:
content = infile.read()
with open(sys.argv[2], 'wb') as output:
for line in content.splitlines():
outsize += len(line) + 1
output.write(line + '\n')
print("Done. Saved %s bytes." % (len(content)-outsize))
(超级用户交叉发布。)
我根据接受的答案做了一个脚本,所以你可以直接转换它,而不需要一个额外的文件,然后删除和重命名。
convert-crlf-to-lf() {
file="$1"
tr -d '\015' <"$file" >"$file"2
rm -rf "$file"
mv "$file"2 "$file"
}
只要确保你有一个像“file1.txt”这样的文件,“file1.txt”。Txt2”不存在,否则将被覆盖。我将此作为存储文件的临时位置。
在Linux上,使用sed很容易将^M (Ctrl + M)转换为*nix换行符(^J)。
在CLI中就像这样,文本中会有一个换行符。然而,\将^J传递给sed:
sed 's/^M/\
/g' < ffmpeg.log > new.log
你可以使用^V (Ctrl + V), ^M (Ctrl + M)和\(反斜杠)当你输入:
sed 's/^V^M/\^V^J/g' < ffmpeg.log > new.log
Use:
tr -d "\r" < file
看一下使用sed的例子:
# In a Unix environment: convert DOS newlines (CR/LF) to Unix format.
sed 's/.$//' # Assumes that all lines end with CR/LF
sed 's/^M$//' # In Bash/tcsh, press Ctrl-V then Ctrl-M
sed 's/\x0D$//' # Works on ssed, gsed 3.02.80 or higher
# In a Unix environment: convert Unix newlines (LF) to DOS format.
sed "s/$/`echo -e \\\r`/" # Command line under ksh
sed 's/$'"/`echo \\\r`/" # Command line under bash
sed "s/$/`echo \\\r`/" # Command line under zsh
sed 's/$/\r/' # gsed 3.02.80 or higher
使用sed -i进行就地转换,例如sed -i 's/..../ '文件。
The solutions posted so far only deal with part of the problem, converting DOS/Windows' CRLF into Unix's LF; the part they're missing is that DOS use CRLF as a line separator, while Unix uses LF as a line terminator. The difference is that a DOS file (usually) won't have anything after the last line in the file, while Unix will. To do the conversion properly, you need to add that final LF (unless the file is zero-length, i.e. has no lines in it at all). My favorite incantation for this (with a little added logic to handle Mac-style CR-separated files, and not molest files that're already in unix format) is a bit of perl:
perl -pe 'if ( s/\r\n?/\n/g ) { $f=1 }; if ( $f || ! $m ) { s/([^\n])\z/$1\n/ }; $m=1' PCfile.txt
注意,这将把文件的统一版本发送到标准输出。如果你想用一个统一的版本替换这个文件,添加perl的-i标志。