How do I split up a line and rearrange its element

2019-07-10 11:51发布

I have some data on a single line like below

abc edf xyz rfg yeg udh

I want to present the data as below

abc
xyz
yeg


edf
rfg
udh

so that alternate fields are printed with newline separated. Are there any one liners for this?

12条回答
冷血范
2楼-- · 2019-07-10 12:37

A shame that the previous perl answers are so long. Here are two perl one-liners:

echo 'abc edf xyz rfg yeg udh'|
  perl -naE '++$i%2 and say for @F; ++$j%2 and say for "",@F'

On older versions of perl (without "say"), you may use this:

echo 'abc edf xyz rfg yeg udh'|
  perl -nae 'push @{$a[++$i%2]},"$_\n" for "",@F; print map{@$_}@a;'
查看更多
beautiful°
3楼-- · 2019-07-10 12:37

Ruby versions for comparison:

ARGF.each do |line|
  groups = line.split
  0.step(groups.length-1, 2) { |x| puts groups[x] }
  puts
  1.step(groups.length-1, 2) { |x| puts groups[x] }
end

ARGF.each do |line|
  groups = line.split
  puts groups.select { |x| groups.index(x) % 2 == 0 }
  puts
  puts groups.select { |x| groups.index(x) % 2 != 0 }
end
查看更多
Evening l夕情丶
4楼-- · 2019-07-10 12:43

Python in the same spirit as the above awk (4 lines):

$ echo 'abc edf xyz rfg yeg udh' | python -c 'f=raw_input().split()
> for x in f[::2]: print x
> print
> for x in f[1::2]: print x'

Python 1-liner (omitting the pipe to it which is identical):

$ python -c 'f=raw_input().split(); print "\n".join(f[::2] + [""] + f[1::2])'
查看更多
The star\"
5楼-- · 2019-07-10 12:44

Another Perl 5 version:

#!/usr/bin/env perl
use Modern::Perl;
use List::MoreUtils qw(part);

my $line = 'abc edf xyz rfg yeg udh';

my @fields = split /\s+/, $line; # split on whitespace

# Divide into odd and even-indexed elements
my $i = 0;
my ($first, $second) = part { $i++ % 2 }  @fields;

# print them out
say for @$first;
say '';          # Newline
say for @$second;
查看更多
The star\"
6楼-- · 2019-07-10 12:46

Just for comparison, here's a few Perl scripts to do it (TMTOWTDI, after all). A rather functional style:

#!/usr/bin/perl -p

use strict;
use warnings;

my @a = split;
my @i = map { $_ * 2 } 0 .. $#a / 2;
print join("\n", @a[@i]), "\n\n",
      join("\n", @a[map { $_ + 1 } @i]), "\n";

We could also do it closer to the AWK script:

#!/usr/bin/perl -p

use strict;
use warnings;

my @a = split;
my @i = map { $_ * 2 } 0 .. $#a / 2;
print "$a[$_]\n" for @i;
print "\n";
print "$a[$_+1]\n" for @i;

I've run out of ways to do it, so if any other clever Perlers come up with another method, feel free to add it.

查看更多
成全新的幸福
7楼-- · 2019-07-10 12:47

you could also just use tr: echo "abc edf xyz rfg yeg udh" | tr ' ' '\n'

查看更多
登录 后发表回答