user1485267
user1485267

Reputation: 1335

get column list using sed/awk/perl

I have different files like below format

Scenario 1 :

File1
no,name
1,aaa
20,bbb

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

I would like to get column list which is having more number of columns and if it is in the same order

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

Scenario 2 :

File1
no,name
1,aaa
20,bbb

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

Expected Results :

Both file headers and positions are different as a message

I am interested in any short solution using bash / perl / sed / awk.

Upvotes: 0

Views: 90

Answers (1)

choroba
choroba

Reputation: 242133

Perl solution:

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 reads the input line by line and runs the code for each line
  • -l removes newlines from input and adds them to printed lines
  • closing the special file handle ARGV makes Perl open the next file and read from it instead of processing the rest of the currently opened file.
  • next makes Perl go back to the beginning of the code, it can continue once more than one input line has been read.
  • sort sorts the lines by length so that we know the longer one is in the second element of the array.
  • index is used to check whether the shorter header is a prefix of the longer one (including the comma after the first header, so e.g. no,names is correctly rejected)

Upvotes: 1

Related Questions