gpt4 book ai didi

bash - 如何将不以特定模式开头的行连接到 UNIX 中的上一行?

转载 作者:行者123 更新时间:2023-11-29 09:06:59 24 4
gpt4 key购买 nike

请查看下面的示例文件和所需的输出,以了解我在寻找什么。

这可以通过 shell 脚本中的循环来完成,但我正在努力获得 awk/sed 一个衬里。

示例文件.txt

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.

期望的输出

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:

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

N;P;D 是在模式空间中保留多行的惯用方式;条件分支部分处理我们追加多行的情况。

这适用于 GNU sed;对于像 Mac OS 中发现的其他 seds,oneliner 必须分开,因此分支和标签在不同的命令中,换行符可能必须转义,我们需要一个额外的分号:

sed -e ':a' -e 'N;/'$'\n''These/!s/'$'\n''/ /;ta' -e 'P;D;' infile

最后一条命令未经测试;见this answer了解不同 SEDS 之间的差异以及如何处理它们。

另一种选择是按字面输入换行符:

sed -e ':a' -e 'N;/\
These/!s/\
/ /;ta' -e 'P;D;' infile

但是,根据定义,它不再是单行代码。

关于bash - 如何将不以特定模式开头的行连接到 UNIX 中的上一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37950170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com