1

I have two files, FL and FR, and would like to select those rows in FL that match the join condition below. However join(1)'s output modifies the layout of FL. Is there a way to guarantee that the join's output will have the same layout (e. g. column order) as FL?

 FL:
 a 1 1 u
 b 2 2 v
 c 3 3 w

 FR:
 2

 join -1 2 -2 1 FL FR

Output:

 2 b 2 v

and I would like

 b 2 2 v

or in other words, the exact row of FL that matches the join condition. In 'real life' the file FL has many columns, and FR has a single column.

YasirA
  • 9,531
  • 2
  • 40
  • 61
Ed Und
  • 33
  • 4

1 Answers1

2

The POSIX specification for join says:

The output line by default shall consist of the join field, then the remaining fields from file1, then the remaining fields from file2. This format can be changed by using the -o option.

Thus, the order of the fields is specified, either explicitly via the -o option or implicitly as stated.

In your example, you would need to specify the -o option:

join -1 2 -2 1 -o "1.1 1.2 1.3 1.4" FL FR

If you have many fields in FL, then you'll need to list them all — unless you can arrange the columns differently. For example, you might post-process the output:

join -1 2 -2 1 FL FR | awk '{ t=$1;$1=$2;$2=t; print }'
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Since there's really one column to relocate, http://stackoverflow.com/questions/17922805/rearrange-columns-using-awk-or-cut-command suggests a few ideas to reposition the first column. – Ed Und Aug 20 '14 at 02:22
  • They're more or less equivalent to what I suggest. The main difference is that the code there might actually preserve spacing between the columns more accurately, though there are caveats about that, and it probably isn't a major issue for you. – Jonathan Leffler Aug 20 '14 at 02:24