Bash 如何使用sed将LF替换为空格,而不是CRLF?

Bash 如何使用sed将LF替换为空格,而不是CRLF?,bash,shell,sed,Bash,Shell,Sed,我有一个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 此解决方案的

我有一个csv文件,它混合了CRLFLF。在某些点上有一个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
此解决方案的问题是,属于CRLFs的LFs也被空格字符替换

使用awk:

$ awk 'BEGIN{RS=ORS="\r\n"}/\n/{sub(/\n/,"")}1' file
smith;pete;he is very nice;1990
brown;mark;he is very nice;2010
taylor;sam;he isvery nice;2009
解释:

$ awk '
BEGIN { RS=ORS="\r\n" }  # set the record separators to CRLF
/\n/ {                   # if there is stray LF in the record
    sub(/\n/,"")         # remove it (maybe " " to replace it with a space)
}1' file                 # output it
在gawk、mawk和Busybox awk上成功测试。BSD awk出现故障,例如:

awk '!/\r$/{printf "%s",$0;next}1' file

使用
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
前面的字符不是
\r

您可以尝试一下
LF
的Unicode吗?如果使用GNU,您可以使用,但可能只有在文件不太大的情况下。
$ 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