我有一个 csv 文件,其中混合了 CRLF 和 LF。在某些点有一个 LF,实际上内容属于前一行。
例子:
smith;pete;he is very nice;1990CRLF
brown;mark;he is very nice;2010CRLF
taylor;sam;he isLF
very nice;2009CRLF
在我的脚本中,我想删除 LF 的所有独立实例。 我尝试使用 sed:
sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' $my_file
此解决方案的问题是属于 CRLF 的 LF 也被替换为空格字符。
最佳答案
与 perl
默认情况下不会删除记录分隔符 - 因此可以轻松操作
$ cat -A ip.txt
smith;pete;he is very nice;1990^M$
brown;mark;he is very nice;2010^M$
taylor;sam;he is$
very nice;2009^M$
$ perl -pe 's/(?<!\r)\n/ /' ip.txt
smith;pete;he is very nice;1990
brown;mark;he is very nice;2010
taylor;sam;he is very nice;2009
$ perl -pe 's/(?<!\r)\n/ /' ip.txt | cat -A
smith;pete;he is very nice;1990^M$
brown;mark;he is very nice;2010^M$
taylor;sam;he is very nice;2009^M$
(?<!\r)\n
使用负面回顾来确保我们替换了 \n
仅当它前面没有 \r
时
修改 OP 的尝试:
$ sed -e ':a' -e 'N' -e '$!ba' -e 's/\([^\r]\)\n/\1 /g' ip.txt
smith;pete;he is very nice;1990
brown;mark;he is very nice;2010
taylor;sam;he is very nice;2009
\([^\r]\)
确保 \n
之前的字符不是 \r
关于bash - 如何使用 sed 将 LF 替换为空格,而不是 CRLF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50737164/