Bash将多行字符串转换为单个换行符分隔字符串

时间:2016-08-19 22:04:18

标签: bash

如何将带有换行符分隔内容的文件转换为如下所示的单行?

blah
blah

blah\nblah

2 个答案:

答案 0 :(得分:1)

或者说: sed -e':a' -e' N' -e' $!ba' -e' s / \ n / \ n / g'
(从其他问题How can I replace a newline (\n) using sed?获得@kenorb的信用)

答案 1 :(得分:0)

多个选项,输出通过管道传输到sed:

<强> AWK

awk 1 ORS='\\n' file | sed 's/..$//'

<强>的Perl:

perl -p -e 's/\n/\\n/' file | sed 's/..$//'

<强> SED

如同在其他帖子中提到的那样,还有一种方法可以在sed中进行。但是,这个:

sed ":a;N;$!ba;s/\n/\\n/g" file

可能无效,因为$!ba可能会在某些系统中扩展到以ba开头的最后一个shell命令。我会建议其他解决方案:

sed ':a;{N;s/\n/\\n/};ba' file

<强>更新

我注意到唯一的标签是bash所以如果你只想使用shell命令:

IFS=$'\n'
last=$(<file wc -l)
cnt=0
while IFS= read -r line ; do
    cnt=$[$cnt +1] 
    if [ $cnt -eq $last ]
    then
        printf "%s" "$line"
    else
        printf "%s" "$line\\n"
    fi  
done < file