You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跨平台下使用Sed/Awk合并奇偶行的实现方法咨询

文本合并需求:将奇数行与后续偶数行合并为单行

原始文本格式:

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

期望转换后的格式:

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

解决方案

方法1:使用sed命令

利用sed的模式空间操作实现奇偶行合并:

sed 'N;s/\n/ /' input.txt
  • N:将下一行内容追加到当前模式空间,此时模式空间包含奇数行和后续偶数行,两行以换行符分隔
  • s/\n/ /:把模式空间内的换行符替换为空格,完成两行合并

如果需要压缩奇数行末尾的多余空格,让格式更紧凑,可调整为:

sed 'N;s/\n\s*/ /' input.txt

\s*会匹配换行后的所有空白字符,替换为单个空格。

方法2:使用awk命令

通过行号判断实现更直观的合并逻辑:

awk 'NR%2==1{line=$0} NR%2==0{print line, $0}' input.txt
  • NR%2==1{line=$0}:行号为奇数时,将当前行内容暂存到变量line中
  • NR%2==0{print line, $0}:行号为偶数时,打印暂存的奇数行内容,再拼接当前偶数行内容,自动用空格分隔

内容的提问来源于stack exchange,提问作者Philip Scot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:20:27