首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Sed/Awk连接奇数行和偶数行-平台无关

Sed/Awk连接奇数行和偶数行-平台无关
EN

Stack Overflow用户
提问于 2022-12-01 13:33:23
回答 3查看 84关注 0票数 0

嗨,我都想做这个

代码语言:javascript
复制
2022-11-14 18:49:59             Indicator is < 3    
1       No
2022-11-14 18:49:59             Indicator is < 10   
1       No
2022-11-14 18:49:59             Indicator is < 22   
1       No
2022-11-14 18:49:59             Indicator is < 1    
1       No

转到

代码语言:javascript
复制
2022-11-14 18:49:59             Indicator is < 3    1       No
2022-11-14 18:49:59             Indicator is < 10   1       No
2022-11-14 18:49:59             Indicator is < 22   1       No
2022-11-14 18:49:59             Indicator is < 1    1       No

我发现你可以在第一、第三、第五、第五、第一、第三、第五、……中使用sed 's/something/some//2'。就这样一个

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2022-12-01 13:44:35

使用模块化的awk来尝试这一点。

代码语言:javascript
复制
$ awk -v val=2 'NR % val == 0{print prev, $0} {prev = $0}' file
2022-11-14 18:49:59             Indicator is < 3     1       No
2022-11-14 18:49:59             Indicator is < 10    1       No
2022-11-14 18:49:59             Indicator is < 22    1       No
2022-11-14 18:49:59             Indicator is < 1     1       No

它查看记录号NR并计算其中的模2。因为第二行的输出为0,所以它将打印前一个prev和当前的$0行。

备注:

  • 打印最后的奇数行是没有定义的,给出的例子很清楚。它甚至可以被看作是一种不打印它们的特性(即使是一个数据集)。
  • --这会使执行时间牢记在心,是一种快速的方法。
票数 0
EN

Stack Overflow用户

发布于 2022-12-01 14:48:50

代码语言:javascript
复制
$ awk '{printf "%s%s", $0, (NR%2 ? OFS : ORS)}' file
2022-11-14 18:49:59             Indicator is < 3     1       No
2022-11-14 18:49:59             Indicator is < 10    1       No
2022-11-14 18:49:59             Indicator is < 22    1       No
2022-11-14 18:49:59             Indicator is < 1     1       No

这与@AndreWildberg's answer之间的细微差别是:

在内存中不包含行,而Andres持有1行(不是问题,只是一个difference).

  • If输入中有奇数行),这将打印所有行(虽然在最后一行末尾为空白,而不是终止换行符),而Andres将删除最后一行(但生成一个终止换行符),例如:

代码语言:javascript
复制
$ seq 5 | awk '{printf "%s%s", $0, (NR%2 ? OFS : ORS)}'
1 2
3 4
5 $

vs

代码语言:javascript
复制
$ seq 5 | awk 'NR % 2 == 0{print prev, $0} {prev = $0}'
1 2
3 4
$
票数 2
EN

Stack Overflow用户

发布于 2022-12-01 21:04:44

另一种方法

代码语言:javascript
复制
$ paste - - <file

2022-11-14 18:49:59             Indicator is < 3        1       No
2022-11-14 18:49:59             Indicator is < 10       1       No
2022-11-14 18:49:59             Indicator is < 22       1       No
2022-11-14 18:49:59             Indicator is < 1        1       No

或(更脆弱)

代码语言:javascript
复制
$ pr -w112 -2at file

2022-11-14 18:49:59             Indicator is < 3        1       No
2022-11-14 18:49:59             Indicator is < 10       1       No
2022-11-14 18:49:59             Indicator is < 22       1       No
2022-11-14 18:49:59             Indicator is < 1        1       No
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74642704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档