我使用sed在目录中组合文本文件行。 命令cd dir&& sed -e' N; s / \ n //' * .txt工作得很好,但是有没有办法可以调整它只合并以**开头的行句和以**结尾的后续句子。所以
This is Line1
**This is Line2
This is Line3**
This is Line4
This is Line5
变为
This is Line1
** This is Line2 This is Line3**
This is Line4
This is Line5
等
答案 0 :(得分:1)
您可以使用此sed
:
sed '/^\*\*/{:loop; N; /\*\*$/{s/\n/ /g;p;d;}; b loop}' file
<强>测试强>
$ cat file
This is Line1
**This is Line2
in between
This is Line3**
This is Line4
**This is Line5
This is Line6**
$ sed '/^\*\*/{:loop; N; /\*\*$/{s/\n/ /g;p;d;}; b loop;}' file
This is Line1
**This is Line2 in between This is Line3**
This is Line4
**This is Line5 This is Line6**
答案 1 :(得分:1)
Sed是你的朋友
$ sed '/^\*\*/{:l1;/\*\*$/!{N;bl1};s/\n/ /g;}' file
This is Line1
**This is Line2 This is Line3**
This is Line4
This is Line5
答案 2 :(得分:1)
sed用于单个行上的简单替换,即全部。对于其他任何你应该使用awk。这将与您的示例输入/输出一起显示:
$ awk '{ORS=(/^\*\*/?FS:RS)}1' file
This is Line1
**This is Line2 This is Line3**
This is Line4
This is Line5
但当然它并没有解决您尚未与我们分享的任何要求(例如,当一行以**开头但下一行没有结束时该怎么做**或反之亦然或一行开头和结尾**或以**开头的行在输入文件的末尾或....)。
答案 3 :(得分:0)
$ cat ip.txt
This is Line1
**This is Line2
This is Line3**
This is Line4
This is Line5
$ # this slurps entire file
$ perl -0777 -pe 's/^(\*\*.*)\n(.*\*\*)$/$1 $2/mg' ip.txt
This is Line1
**This is Line2 This is Line3**
This is Line4
This is Line5
$ # can use this if testing start of line for ** is enough
$ perl -pe 's/\n/ / if /^\Q**/' ip.txt
参考:How do I search and replace across multiple lines with Perl?