如何合并奇数行和偶数行? [英] How can I combine odd and even numbered lines?

查看:59
本文介绍了如何合并奇数行和偶数行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将每个偶数行与其上方的行合并.类似的东西:

I want to combine every even-numbered line with the line above it. Something like:

Line one,csv,csv,csv
Line two,csv,csv
Line three,csv,csv,csv,csv
Line four,csv

结果应该是这样的:

Line one,csv,csv,csv,Line two,csv,csv
Line three,csv,csv,csv,csv,Line four,csv

任何想法如何在 Perl 或 sed/awk 中实现?

Any ideas how to achieve that in either Perl or sed/awk?

推荐答案

Perl 的内置变量 $. 会告诉你行号.<代码>$.如果 $. 为奇数,% 2 将为 1,否则为 0.这是一个独立的例子;

Perl's builtin variable $. will tell you the line number. $. % 2 will be 1 if $. is odd, and 0 otherwise. Here is a self-contained example;

#!/usr/bin/perl

use strict; use warnings;

my $buffer;

while (my $line = <DATA>) {
    if ($. % 2) {
        chomp $line;
        $buffer = $line;
    }
    else {
        print join(",", $buffer, $line);
    }
}

__DATA__
Line one,csv,csv,csv
Line two,csv,csv
Line three,csv,csv,csv,csv
Line four,csv

输出:

C:\Temp> tt
Line one,csv,csv,csv,Line two,csv,csv
Line three,csv,csv,csv,csv,Line four,csv

这篇关于如何合并奇数行和偶数行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆