使用 sed:
sed ':a;N;/\nThese/!s/\n/ /;ta;P;D' infile
导致
These are leaves.
These are branches.
These are greenery which gives oxygen, provides control over temperature and maintains cleans the air.
These are tigers
These are bears and deer and squirrels and other animals.
These are something you want to kill Which will see you killed in the end.
These are things you must to think to save your tomorrow.
下面是它的工作原理:
sed '
:a # Label to jump to
N # Append next line to pattern space
/\nThese/!s/\n/ / # If the newline is NOT followed by "These", append
# the line by replacing the newline with a space
ta # If we changed something, jump to label
P # Print part until newline
D # Delete part until newline
' infile
The N;P;D
是在模式空间中保留多行的惯用方法;条件分支部分负责处理我们追加多行的情况。
这适用于 GNU sed;对于其他 sed,例如 Mac OS 中的 sed,必须将 oneliner 分开,以便分支和标签位于单独的命令中,换行符可能必须转义,并且我们需要一个额外的分号:
sed -e ':a' -e 'N;/'$'\n''These/!s/'$'\n''/ /;ta' -e 'P;D;' infile
This last command is untested; see this answer https://stackoverflow.com/a/24276470/3266847 for differences between different seds and how to handle them.
另一种选择是按字面输入换行符:
sed -e ':a' -e 'N;/\
These/!s/\
/ /;ta' -e 'P;D;' infile
但根据定义,它不再是一句俏话。