首页 > 解决方案 > 使用 sed/awk/perl 获取列列表

问题描述

我有不同的文件,如下格式

方案 1:

File1
no,name
1,aaa
20,bbb

File2
no,name,address
5,aaa,ghi
7,ccc,mn

我想获得列数更多的列列表,如果它的顺序相同

**Expected output for scenario 1 :**
no,name,address

方案 2:

File1
no,name
1,aaa
20,bbb

File2
no,age,name,address
5,2,aaa,ghi
7,3,ccc,mn

预期成绩 :

Both file headers and positions are different as a message

我对使用 bash / perl / sed / awk 的任何简短解决方案感兴趣。

标签: perlawksed

解决方案


Perl 解决方案:

perl -lne 'push @lines, $_;
           close ARGV;
           next if @lines < 2;
           @lines = sort { length $a <=> length $b } @lines;
           if (0 == index "$lines[1],", $lines[0]) {
               print $lines[1];
           } else {
               print "Both file headers and positions are different";
           }' -- File1 File2
  • -n逐行读取输入并运行每一行的代码
  • -l从输入中删除换行符并将它们添加到打印行
  • 关闭特殊文件句柄ARGV使 Perl 打开下一个文件并从中读取,而不是处理当前打开的文件的其余部分。
  • next使 Perl 回到代码的开头,一旦读取了不止一个输入行,它就可以继续。
  • sort按长度对行进行排序,以便我们知道较长的行在数组的第二个元素中。
  • index用于检查较短的标头是否是较长标头的前缀(包括第一个标头后的逗号,因此 egno,names被正确拒绝)

推荐阅读