Linux 如何获取线对并连接?

Linux 如何获取线对并连接?,linux,perl,shell,text,Linux,Perl,Shell,Text,我有一个文件,其格式如下: instance1 field1 instance1 field2 instance2 field1 instance2 field2 instance3 field1 instance3 field2 ... 我想要一个oneliner,这样它就可以转换为: instance1 field1 field2 instance2 field1 field2 instance3 field1 field3 等等 我可以编写以下类型的perl脚本: while (<

我有一个文件,其格式如下:

instance1 field1
instance1 field2
instance2 field1
instance2 field2
instance3 field1
instance3 field2
...
我想要一个oneliner,这样它就可以转换为:

instance1 field1 field2
instance2 field1 field2
instance3 field1 field3
等等

我可以编写以下类型的perl脚本:

while (<STDIN>)
{
 $line = $_;
 $line2 = <STDIN>;
 chomp $line; chomp $line2;
 print "$line $line2\n";
}
while()
{
$line=$\;
$line2=;
chomp$line;chomp$line2;
打印“$line$line2\n”;
}
但我更希望有一个单行线。有什么想法吗?

sed和awk:

sed '$!N;s/\n/ /' file.txt | awk '{print $1, $2, $4}'

使用行号
$的两种解决方案。

perl -lane 'print $. % 2 ? @F[0,1] : " $F[1]\n"' file

这个perl一行程序有点长,但它可以工作

perl -ne 'BEGIN{%h}{chomp;($k,$v) = split(/\s/,$_);$h{$k} .= qq( $v)}END{foreach( sort keys %h){print qq($_$h{$_}\n)}}' file
奖励:解决方案允许您将来有两(2)个以上的字段,而无需更新脚本。

使用gnu-sed

sed 'N;s/\n/ /;s/ \w*//2' file
使用awk

awk '{printf (NR%2)?$0 FS:$2 RS}' file

您可能不会使用这种通用的方法,但为了以防万一,请按第一个字段列出以下组:

perl -lane'
   push @{ $i{ $F[0] } }, $F[1];
   END {
      print join "\t", $_, @{ $i{$_} }
         for sort keys %i;
   }
'

使用
粘贴
和GNU
剪切

<file paste -d ' '  - - | cut --complement -f3 -d ' '
instance1 field1 field2
instance2 field1 field2
instance3 field1 field2

每行一条记录,还是一行一个文件?噢,糟糕,格式不正确。让我来修理@RamanThough这对于EOFs来说有点敏感…
cat file.txt | sed'$!Ns/\n/'-|awk'{print$1,$2,$4}'
对我有用,但是
sed'$!Ns/\n/'-|awk'{print$1,$2,$4}'
没有。code Golf:
awk'$0=(NR%2?$0 FS:$2 RS)'ORS=文件
<file paste -d ' '  - - | cut --complement -f3 -d ' '
instance1 field1 field2
instance2 field1 field2
instance3 field1 field2