【发布时间】:2020-06-16 21:47:55
【问题描述】:
我有一个包含以下数据的文件:
;Citation1 begins here and contains characters including , . and numbers
DATA 1 259.85 101000 0.094837707 0.9089 /
2 266.07 101000 0.097842938 0.8997 /
3 270.95 101000 0.105071894 0.8899 /
4 273.35 101000 0.112016587 0.8849 /
5 278.75 101000 0.134569045 0.87 /
;Citation2 begins here and contains characters including , . and numbers but
;this one continues on the next line
DATA 1 259.85 101000 0.094837707 0.9089 /
2 266.07 101000 0.097842938 0.8997 /
3 270.95 101000 0.105071894 0.8899 /
4 273.35 101000 0.112016587 0.8849 /
5 278.75 101000 0.134569045 0.87 /
我想将所有行打印到一个新文件中。但是,当连续的行以相同的字符(此处为“;”)开头时,我想将它们连接到同一行。因此,上述输入文件将显示为:
;Citation1 begins here and contains characters including , . and numbers
DATA 1 259.85 101000 0.094837707 0.9089 /
2 266.07 101000 0.097842938 0.8997 /
3 270.95 101000 0.105071894 0.8899 /
4 273.35 101000 0.112016587 0.8849 /
5 278.75 101000 0.134569045 0.87 /
;Citation2 begins here and contains characters including , . and numbers but this one continues on the next line
DATA 1 259.85 101000 0.094837707 0.9089 /
2 266.07 101000 0.097842938 0.8997 /
3 270.95 101000 0.105071894 0.8899 /
4 273.35 101000 0.112016587 0.8849 /
5 278.75 101000 0.134569045 0.87 /
我尝试过使用不同的 awk 命令变体,例如:
awk '/;/ && last {printf "%s","\n"last;$0}{printf "%s",$0}END{print} /;/{last=$0}' input.txt > output.txt
但没有成功。
【问题讨论】:
-
欢迎来到 SO,在 SO 上,我们鼓励用户添加他们为解决自己的问题而付出的努力,所以请添加相同的内容并让我们知道。
-
为什么不专注于三个规则?第一个查找
/^;/(连接所有行,从字符2 开始,递增计数器n跳到下一条记录)下一个检查是否n > 0(打印以';'为前缀并附加'\n'的连接行,重置您的字符串和计数器,跳到下一个)和最终规则1(默认打印)。试一试,通过提供 A Minimal, Complete, and Verifiable Example (MCVE) 告诉我们您遇到的问题。 -
我编辑了帖子以解决第一条评论。我尝试了那条线的一百万种变体,但没有运气。通过第二条评论,我理解了逻辑,但我仍在尝试找出正确的语法来实现它。谢谢!
-
@user13758913 干得好。您会看到我会在 Ed 的答案下方发布的内容(在完美的
awk解决方案上很难与 Ed 竞争)。访问 cmets 中提供的链接 Ed 以调查和纠正您在数据文件中遇到的任何杂散行结束问题。两种解决方案都可以使用从您的问题中复制和粘贴的输入来满足您的要求。
标签: awk concatenation match