删除两个单词之间的换行符

时间:2014-08-02 21:02:01

标签: bash awk sed formatting sh

我有一个看起来像的文件:

name: charles
key1: how
are
you?
name: erika
key2: I'm
fine,
thanks
name: ...

如何删除“key \ d +”和“name:”之间的新行?它应该是这样的:

name: charles
key1: how are you?
name: erika
key2: I'm fine, thanks
name: ...

我正在尝试使用sed或awk但没有任何成功。有没有办法清理这些线?

有没有办法删除“key \ d +:”和“\ w +:”之间的换行符?

4 个答案:

答案 0 :(得分:4)

这样的事情?

kent$  awk '/^key.:/{p=1}/^name:/{p=0}
            {if(p)printf "%s",$0;else printf "%s%s\n", (NR==1?"":RS),$0}' file
name: charles
key1: howareyou?
name: erika
key2: I'mfine,thanks
name: ...

处理空格:

awk '/^key.:/{p=1}/^name:/{p=0}
    {if(p)printf "%s%s",(/^key.:/?"":" "),$0;
    else printf "%s%s\n", (NR==1?"":RS),$0}' file

输出:

name: charles
key1: how are you?
name: erika
key2: I'm fine, thanks
name: ...

答案 1 :(得分:2)

这可能适合你(GNU sed):

sed ':a;$!N;/\n.*:/!s/\n/ /;ta;P;D' file

如果第二行没有以关键字:开头,请在模式空间中保留两行并从第一行中删除换行符。当关键字和:遇到打印然后删除第一行时。

答案 2 :(得分:1)

替代awk解决方案。

awk '
  {
    if      (NR == 1)                s = ""
    else if ($1 ~ /^[[:alnum:]]+:$/) s = RS
    else                             s = " "
    printf "%s%s", s, $0
  }
  END {print ""}
'<<EOF
name: charles
key1: how
are
you?
name: erika
key2: I'm
fine,
thanks
EOF
name: charles
key1: how are you?
name: erika
key2: I'm fine, thanks

答案 3 :(得分:-1)

以下作品,但表现显然不是最好的:

cat file.txt | while read x;do echo "$x" | grep -q ':' && echo; echo -ne "$x "; done | sed -n 's/ $//p'

name: charles
key1: how are you?
name: erika
key2: I'm fine, thanks
name: ...