Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two text files using bash

Tags:

bash

I have two text files that I wish to combine in bash so that every line in one file is combined with every file in the other file.

file1.txt

abc123
def346
ghj098

file2.txt

PSYC1001
PSYC1002
PSYC1003

I want to combine them so that line 1 of file1 is added to every line of file2, with a pipe de-limiter | in between them.

e.g.

PSYC1001|abc123
PSYC1002|abc123
PSYC1003|abc123

Then the same for the other lines in file1 so I would end up with

PSYC1001|abc123
PSYC1002|abc123
PSYC1003|abc123
PSYC1001|def346
PSYC1002|def346
PSYC1003|def346
PSYC1001|ghj098
PSYC1002|ghj098
PSYC1003|ghj098<

I've been doing similar simpler text things in bash by copying examples from this site, but I've not found an example that can do this. Would love to hear your suggestion. I know it must be simple but I've not worked it out yet.

like image 669
A1277 Avatar asked Dec 10 '22 08:12

A1277


1 Answers

The shortest one - join command:

join -j2 -t'|' -o2.1,1.1 file1 file2
  • -t'|' - input/output field separator
  • -o FORMAT - FORMAT is one or more comma or blank separated specifications, each being FILENUM.FIELD or 0

The output:

PSYC1001|abc123
PSYC1002|abc123
PSYC1003|abc123
PSYC1001|def346
PSYC1002|def346
PSYC1003|def346
PSYC1001|ghj098
PSYC1002|ghj098
PSYC1003|ghj098
like image 60
RomanPerekhrest Avatar answered Dec 28 '22 20:12

RomanPerekhrest