【问题标题】:Bash turning multi-line string into single newline separated string [duplicate]Bash将多行字符串转换为单个换行符分隔的字符串[重复]
【发布时间】:2016-12-27 03:50:21
【问题描述】:

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

blah
blah

进入

blah\nblah

【问题讨论】:

  • 你想在两行之间使用文字\n吗?

标签: bash


【解决方案1】:

通过管道输出到 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

【讨论】:

    【解决方案2】:

    或 sed: sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\n/g'
    (学分来自其他问题@kenorb How can I replace a newline (\n) using sed?

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 2021-10-08
      • 2021-08-20
      • 2013-06-05
      • 2012-11-08
      • 1970-01-01
      相关资源
      最近更新 更多