How to combine two text files using bash

I have two text files that I want to combine in bash so that each line from one file is merged with each file in another file.

file1.txt

abc123
def346
ghj098

file2.txt

PSYC1001
PSYC1002
PSYC1003

I want to combine them so that line 1 of is file1added to each line file2with a channel delimiter |between them.

eg.

PSYC1001|abc123
PSYC1002|abc123
PSYC1003|abc123

Then the same goes for the other lines in file1, so I get

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

I did similar simple text things in bash, copying examples from this site, but I did not find an example that can do this. I would like to hear your suggestion. I know this should be easy, but I haven't developed it yet.

+4
source share
4 answers

- join:

join -j2 -t'|' -o2.1,1.1 file1 file2
  • -t'|' - /
  • -o FORMAT - FORMAT - , FILENUM.FIELD 0

:

PSYC1001|abc123
PSYC1002|abc123
PSYC1003|abc123
PSYC1001|def346
PSYC1002|def346
PSYC1003|def346
PSYC1001|ghj098
PSYC1002|ghj098
PSYC1003|ghj098
+5

awk :

awk -v OFS="|" 'NR==FNR{a[NR]=$0;c=NR;next}{for(i=1;i<=c;i++){print a[i],$0}}' file2 file1

:

kent$  awk -v OFS="|" 'NR==FNR{a[NR]=$0;c=NR;next}{for(i=1;i<=c;i++){print a[i],$0}}' f2 f1
PSYC1001|abc123
PSYC1002|abc123
PSYC1003|abc123
PSYC1001|def346
PSYC1002|def346
PSYC1003|def346
PSYC1001|ghj098
PSYC1002|ghj098
PSYC1003|ghj098 
+4

Here are two ways to do this in regular bash:

while IFS= read -u3 -r elem1; do 
    while IFS= read -u4 -r elem2; do 
        echo "$elem2|$elem1"
    done 4<file2.txt
done 3<file1.txt
mapfile -t f1 < file1.txt
mapfile -t f2 < file2.txt
for elem1 in "${f1[@]}"; do 
    for elem2 in "${f2[@]}"; do 
        echo "$elem2|$elem1"
    done
done
+3
source

bash only

a1=( $(<f1) )
a2=( $(<f2) )

for i in "${a2[@]}"
do
 for j in "${a1[@]}"
  do
   echo "${j}|${i}"
 done
done
+1
source

Source: https://habr.com/ru/post/1691987/


All Articles