bashfile-managerfile-mapping

merge contents of two files into one file by bash command


i have two file like blow format and need to marge two file in below format (bash command)

1st row of 1st file + 1st row of 2nd file 2nd row of 1st file + 2nd row of 2nd file

Example :

file1

a
b
c
d

file2

1
2
3
4

expected output file

a,1
b,2
c,3
d,4

Solution

  • #!/usr/bin/env bash
    
    file1="$1"
    file2="$2"
    
    file1_contents=$(<"$file1")
    file2_contents=$(<"$file2")
    
    read -ra array1 <<< "$file1_contents"
    read -ra array2 <<< "$file2_contents"
    
    final_string=""
    for ((i=0; i<"${#array1[@]}"; i++));
    do
      final_string+="${array1[i]},${array2[i]} "
    done
    
    echo "$final_string"
    

    This bash script reads 2 command line arguments, file1 and file2. Assuming file one has a b c d and file2 has 1 2 3 4 as their respective contents, then the script will read the contents of both files and convert the contents into an array using the read command. The -a option will make the read command convert the file1_contents into an array and store the result in the variable array1. It will do the same for the contents of the second file.

    We then declare a final_string variable that will hold the final result. Afterwards we loop through the first array and on each iteration of the loop, we take the current element in the first array and concatenate it to the element at the same position of the second array and this we add to the final_string.

    Hope it helps.